Saturday 15 August 2015

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


In my table there are parent / child relations, along with the lines of parent.id, the ID is a column in which the quantity , And another ID represents a grand-parent, such as:

  id parent.id qty organization 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 102 102 8 6 1 102   

This is to show that ID is 1 parent, and ID2 and 3 children who are ID 1 , And id 1, 2, and 3 belong to all grandparents.

I would like to know whether a child or a parent has Qt = 0, what are all the other id related to that parent, and what are all parents related to that grandparent? For example, I want to see a report that shows me:

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

appreciate any help that you can offer to handle MS SQL 2000 (yes, I know) is.

try it

 select  from tablename where it exists (selection) From 1 to Tablean x to x.parent_id = a.parent_id and qty = 0)   

Example:

 ; Select as the whistle (1 ID, 1 parent, 1 quantity, 100 Union Union All selected 2,1,0,100 Union Select all 3,1,4,100 Union All selected 4,4,1,101 Union of all Select 5,4,2,101 Union Select All 6,6,1,102 Union Select All 7,6,0,102 Select All Union 8,6,1,102) * Choose from CTA * where exists (1 from CTE Select where x.parent_id = a.parent_id and qty = 0)   



No comments:

Post a Comment