Search code examples
t-sqlsql-server-2000

Build a query that pulls records based on a value in a column


My table has a parent/child relationship, along the lines of parent.id,id. There is also a column that contains a quantity, and another ID representing a grand-parent, like so:

id  parent.id qty Org
1   1         1   100
2   1         0   100
3   1         4   100
4   4         1   101
5   4         2   101
6   6         1   102
7   6         0   102
8   6         1   102

What this is supposed to show is ID 1 is the parent, and ID 2 and 3 are children which belongs to ID 1, and ID 1, 2, and 3 all belong to the grandparent 100.

I would like to know if any child or parent has QTY = 0, what are all the other id's associated to that parent, and what are all the other parents associated with that grandparent?

For example, I would want to see a report that shows me this:

Org  id  parent.id  qty
100  1   1          1
100  2   1          0
100  3   1          4
102  6   6          1
102  7   6          0
102  8   6          1

Much appreciate any help you can offer to build a MS SQL 2000 (yeah, I know) query to handle this.


Solution

  • Try this

    select * from tablename a
    where exists (select 1 from tablename x 
                  where x.parent_id = a.parent_id and qty = 0)
    

    Example:

    ;with cte as
    ( select 1 id,1 parent_id, 1 qty, 100 org
      union all select 2,1,0,100
      union all select 3,1,4,100
      union all select 4,4,1,101
      union all select 5,4,2,101
      union all select 6,6,1,102
      union all select 7,6,0,102
      union all select 8,6,1,102
    
    )
    select * from cte a
    where exists (select 1 from cte x 
                  where x.parent_id = a.parent_id and qty = 0)
    

    SQL DEMO HERE