How do I find records in a database that associate on on key and don't include a certain value on any of them?

StackOverflow https://stackoverflow.com/questions/23618835

  •  21-07-2023
  •  | 
  •  

Question

To start off, here are my tables where same name columns are foreign keys:

Lines_Origin_Table columns: line_origin_key, type
Line_Items_Table columns: line_items_key, line_origin_key, bill_key
Bills_Table columns: bill_key, bill_status, bill_code

I'm trying to find instances where all a Bills_Table record have bill_status = 1 and bill_code = 2 and and no Lines_Origin_Table record that associates to this Bills_Table record has a type of 'C'.

I have something like

SELECT lit.line_origin_key 
    FROM Line_Items_Table lit (NOLOCK) 
    INNER JOIN Bills_Table bt (NOLOCK) ON lit.bill_key= bt.bill_key
    INNER JOIN Lines_Origin_Table lot (NOLOCK) ON lit.line_origin_key= lot.line_origin_key
    WHERE bt.bill_status = 1 
    AND bt.bill_code = 2 
    AND 'C' NOT IN (SELECT type
                        FROM Lines_Origin_Table lot2 (NOLOCK) 
                        INNER JOIN Line_Items_Table lit2 (NOLOCK) ON lot2.line_item_key = lit2.Line_Item_Key 
                        INNER JOIN Bills_Table bt2 (NOLOCK) ON bt2.bill_key= bt.bill_key)

, but it returns no records. If I run all but the final NOT 'C' condition and then check the data that returns, I can find ones that match what I'm looking for, but I need something that does it without manual inspection of the intermediate data.

Was it helpful?

Solution

SELECT lit.line_origin_key
FROM Bills_Table bt
INNER JOIN Line_Items_Table lit
    ON bt.bill_key = lit.bill_key
WHERE bt.bill_status = 1 
AND bt.bill_code = 2 
AND NOT EXISTS( SELECT 1 FROM Lines_Origin_Table 
                WHERE line_origin_key = lit.line_origin_key
                AND [type] = 'C')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top