我有两张桌子: 客户(父母) 协议(儿童)
如果许多协议statusID中的一个具有特定值(例如,已注销),我需要在查询中显示某个值。两个表之间的连接是CustomerID。
因此,如果客户有3个协议,2个协议的statusID为1,其中1个有5个,我需要显示一定的值。我只想在此查询中返回一行而不是在典型连接中出现的3行
有什么建议吗?
答案 0 :(得分:0)
select
CustomerID,
max(case when StatusId = 1 then 1 else 0 end) as HasStatus1,
max(case when StatusId = 2 then 1 else 0 end) as HasStatus2
--etc.
from Customer
left join Agreement
group by Customer.CustomerID
由于分组,每个客户将返回一行,并显示标记表明他们是否在每个关注状态中都有任何协议 - 如果您正在查找单个CustomerID
,那么您显然在那里抛出where语句,你也可以删除该组(当然,你必须从结果集中删除CustomerID
)。
考虑到您的评论,您需要以下内容:
;with grouped as (
select
CustomerID,
max(case when StatusId = 1 then 1 else 0 end) as HasStatus1,
max(case when StatusId = 2 then 1 else 0 end) as HasStatus2,
max(case when StatusId = 5 then 1 else 0 end) as HasStatus5
--etc.
from Customer
left join Agreement
group by Customer.CustomerID
)
select
CustomerID,
case
when HasStatus5 = 1 then 5
when (HasStatus1 = 1 OR HasStatus2) and <no other status>) then 1
--etc.
else <Can't return StatusId here because there might be more than one... so whatever your default actually is> END as Result
from grouped