在同一行上按两个字段分组

时间:2013-09-19 08:34:06

标签: sql tsql

如果这非常基本或我遗漏了一些细节,那么非常抱歉。

我有查询

select   #FBorders1.QuestCode
    ,COUNT(Distinct #FBOrders1.CustomerID)as UniqueCust
from #FBOrders1
group by #FBOrders1.QuestCode

此节目显示已订购特定库存商品(QuestCode)的唯一客户

我现在需要显示有多少这些独特的客户已经下了2个,​​3个或4个订单..第2,第3,第4个订单不会记录针对他们的QuestCode

表由OrderID,CustomerID,QuestCode

组成

提前致谢

1 个答案:

答案 0 :(得分:0)

试试这段代码,

select a.QuestCode ,COUNT(distinct a.CustomerID)as UniqueCust,
count(distinct  (case when a.questcode = b.questcode and  a.customerid = b.customerid then  b.customerid else 0 end) )-2,
count(distinct  (case when a.questcode = b.questcode and  a.customerid = b.customerid then  b.customerid else 0 end) )-3,
count(distinct  (case when a.questcode = b.questcode and  a.customerid = b.customerid then  b.customerid else 0 end) )-4
from fborder a inner join
fborder b on a.customerid = b.customerid
group by a.QuestCode