限制分组

时间:2017-12-22 15:44:40

标签: sql sql-server

我有2张桌子。一个具有parent_Work_orders,另一个具有child_work_order。它们由WO#链接。这两个表都有一个状态列,其值为' 1'(有效)或' 0'(无效)。现在,parent_WO可能已关闭(未激活),但该WO的子项可能处于活动状态。

我想以这样一种方式对它们进行分组: 1.如果父项处于活动状态,则显示所有child_WO,其中parent_WO是该组的标题。 2.如果父级未激活,但其中一个child_WO处于活动状态,则再次显示附加到该父级的每个WO(活动与否)。 3.如果父级已关闭且chid_WO也已关闭,则不显示。

父母表

WO  part  status  duedate
1   abc   0       1/2/2018
2   abc   1       1/2/2018
3   abc   0       1/2/2018

儿童表

WO  part  status  duedate
1   abc   1       1/2/2018
1   aaa   0       1/2/2018
2   abc   0       1/2/2018
2   abc   0       1/2/2018
3   abc   0       1/2/2018
3   qqq   0       1/2/2018

我只希望WO 1和2显示我何时加入有限制的表格。这可能吗?

OUTOUT

    WO  part  status  duedate
1   abc   0       1/2/2018
1   abc   1       1/2/2018
1   aaa   0       1/2/2018
2   abc   1       1/2/2018
2   abc   0       1/2/2018
2   abc   0       1/2/2018

3 个答案:

答案 0 :(得分:1)

使用cte获取满足条件的所有工单,然后使用它从父表和子表中获取行。

with all_wos as (select wo
                 from child
                 group by wo
                 having max(status)=1
                 union all
                 select wo from parent where status=1
                ) 
select p.*,1 as col
from parent p
where wo in (select wo from all_wos)
union all
select c.*,2 as col
from child
where wo in (select wo from all_wos) 
order by col,status,duedate 

答案 1 :(得分:1)

除了Vamsi的解决方案,您还可以使用SELECT

WHERE EXISTS(any row with this WO where Status=1 in either table)解决此问题

答案 2 :(得分:0)

您可以UNION两个表并选择至少status = 1的所有WO。

  

parent_WO是小组的标题

您可以使用额外的优先级列并按其排序。

;with temp as
(
    select *, 1 as ObjPriority from @Parent
    UNION ALL 
    select *, 2 as ObjPriority from @Child
)
select * from temp
where WO IN ( select distinct WO from temp where status = 1) -- at least status = 1
order by ObjPriority -- parent is header
相关问题