sql server 2008 r2 - Filtering specific sql resultset and stacking two tables vertically -
i have sql statement
select parent.wonum, parent.parent, parent.status, parent.description, child.wonum child_wonum, child.parent child_parent, child.status child_status (select * max7503.dbo.workorder w w.parent null , w.worktype = 'insp' , w.changeby = 'xli') parent left join (select * max7503.dbo.workorder child child.parent not null , child.worktype = 'insp' , changeby = 'xli') child on parent.wonum = child.parent parent.status = 'comp'
my result set :
a parent can have multiple children. how these 2 linked parents wonum equal child's parent.
looking not not join table side side. stack them vertically. have tried using union must follow logic have here. flow must if parent's status equal comp query children associated parent. if parent status not comp. not query children associated it. new sql insight helpful thank you.
edit: looking achieve have 1 table pull from.
workorder table
wonum parent status worktype ===== ====== ====== ======== 1000 null comp insp 1002 1000 comp insp 1005 1000 comp insp 1006 null appr insp 1008 1006 comp insp 1009 1006 comp insp 1010 1006 appr insp 1011 1006 comp insp
desired output
wonum parent status worktype ===== ====== ====== ======== 1000 null comp insp 1002 1000 comp insp 1005 1000 comp insp
by small sample data. have 2 parents ( 1000 , 1006). 1006 still has children elements status of appr. query parent , children associated parent. status comp.
i'm not sure follow you're after here, if want 'stack' records , they're coming same table, why not use order by
:
select * max7503.dbo.workorder worktype = 'insp' , changeby = 'xli' order coalesce(parent,wonum) ,parent ,wonum
if that's not you're after, showing desired output sample data helpful.
update: based on updated question it's apparent need join
filter records, best done in recursive cte, , after filtering can use order by
format output:
;with cte (select wonum, parent table1 status = 'comp' , parent null union select a.wonum, a.parent table1 join cte b on a.parent = b.wonum status = 'comp') select * table1 worktype = 'insp' , exists (select * cte b a.wonum = b.wonum) order coalesce(parent,wonum) ,parent ,wonum
demo: sql fiddle
Comments
Post a Comment