我有下表:
OrderId ContactId IsPrimaryContact FirstName
1 1 1 John
1 2 0 Steve
2 3 1 Mary
我想获取每个订单的联系人数量,并且仅检索主要联系人。结果将如下所示:
Contacts OrderId ContactId FirstName
2 1 1 John
1 2 3 Mary
使用SQL Server 2012
select x.contacts, y.orderid, y.contactid, y.firstname
from (select count(*) as contacts, orderid from tbl group by orderid) x
join tbl y
on x.orderid = y.orderid
where y.isprimarycontact = 1
小提琴: http ://sqlfiddle.com/#! 6/62149/2/0
以上答案假设:1.每个订单最多只能有一个主要联系人2.每个订单确实都有一个主要联系人
下面的答案将解决订单中未列出主要联系人的可能性(尽管contactid和firstname字段同样为空白):
select x.contacts, x.orderid, y.contactid, y.firstname
from (select count(*) as contacts, orderid from tbl group by orderid) x
left join tbl y
on x.orderid = y.orderid
and y.isprimarycontact = 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句