Tsql 从子表中获取特定值

Tsql 从子表中获取特定值,tsql,Tsql,我有两张桌子: 客户母公司 协议子女 如果多个协议statusID中的一个具有特定值(例如注销),我需要在查询中显示特定值。这两个表之间的连接是CustomerID 因此,如果一个客户有3个协议,2个协议的statusID为1,一个协议的statusID为5,那么我需要显示一个特定的值。我只想在这个查询中返回一行,而不是在典型联接中返回3行 有什么建议吗 select CustomerID, max(case when StatusId = 1 then 1 else 0 end

我有两张桌子: 客户母公司 协议子女

如果多个协议statusID中的一个具有特定值(例如注销),我需要在查询中显示特定值。这两个表之间的连接是CustomerID

因此,如果一个客户有3个协议,2个协议的statusID为1,一个协议的statusID为5,那么我需要显示一个特定的值。我只想在这个查询中返回一行,而不是在典型联接中返回3行

有什么建议吗

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
这将根据group by为每个客户返回一行,并用标志指示他们是否在每个关注状态下都有任何协议-如果您查找单个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

当有两个statid=1的协议和一个statid=5的协议来做你的事情时,你特别想要吗?或者这只是一个例子?Thanos,我已经研究过使用FOR XML将所有值放在一个CTE中的一个字符串中,但是考虑到我关心的数据量,这只是一个例子,我需要编写4种不同的场景。如果all=1,则返回1。如果1=5,则返回5。如果all=1或2,则返回1。Else返回状态ID