使用 group by 在另一个 table 中添加行存在标志

Add flag for row existence in another table with group by

对于下面的查询,我想要一个名为 isHold 的标志,它将计算为 0 如果 onHold table 中不存在视图 viewBills 中的 billNo 并且 1 否则

select max(t.id) TrackingID , max(vb.billNo) billNo, cb.id  ,
max(case when vb.[count] > 1 then 1 else 0 end) isMultiple ,
max(case when t.TrackingID = 31 then 1 else 0 end) IsCancelled,
max(case when exists (select 1 from OnHold oh
where oh.billNo = billNo) then 1 else 0 end) IsHold

from viewBills vb
join tracking t on vb.billNo = t.billNo
join customerBills cb on vb.billNo = cb.billNo 
join customerPieces cp on  cb.id = cp.customerBillId
where cb.statusid <> 3
group by cb.id

我在执行时遇到这个错误

Cannot perform an aggregate function on an expression 
containing an aggregate or a subquery.

这是合理的,但如何实现呢?

您可以使用 outer applyleft join 将逻辑移动到 FROM 子句:

select max(t.id) as TrackingID , max(vb.billNo) as billNo, cb.id ,
       max(case when vb.[count] > 1 then 1 else 0 end) as isMultiple,
       max(case when t.TrackingID = 31 then 1 else 0 end) as IsCancelled,
       max(case when oh.billNo is not null then 1 else 0 end) as IsHold
from viewBills vb join
     tracking t
     on vb.billNo = t.billNo join
     customerBills cb
     on vb.billNo = cb.billNo  join
     customerPieces cp
     on cb.id = cp.customerBillId outer apply
     (select top (1) oh.*
      from OnHold oh
      where oh.billNo = cb.billNo
     ) oh
where cw.statusid <> 3
group by cb.id;

您可以使用 LEFT OUTER JOIN 并按如下所示进行聚合:

select max(t.id) TrackingID , max(vb.billNo) billNo, cb.id  ,
max(case when vb.[count] > 1 then 1 else 0 end) isMultiple ,
max(case when t.TrackingID = 31 then 1 else 0 end) IsCancelled,
max(case when oh.billNo IS NOT NULL then 1 else 0 end) IsHold

from viewBills vb
join tracking t on vb.billNo = t.billNo
join customerBills cb on vb.billNo = cb.billNo 
join customerPieces cp on  cb.id = cp.customerBillId
LEFT OUTER JOIN OnHold oh ON oh.billNo = vb.billNo
where cb.statusid <> 3
group by cb.id