每个不同的返回计数

时间:2014-01-06 14:03:28

标签: sql sql-server

我有以下表格:

ORDER

OrderId
-------
Order1
Order2
Order3

CUSTOMERORDER

OrderId  CustomerId
-------  ----------
Order1   Cust1
Order1   Cust2
Order2   Cust3
Order3   Cust1

查询

select distinct count(*) as CustomersPerOrder
from CustomerOrder
group by CustomerOrder.OrderId
order by CustomersPerOrder

返回

CustomersPerOrder
-----------------
1
2

也就是说,有些订单有1个客户,有些有2个。我也想知道有多少订单有1个客户,有多少订单有2个:

CustomersPerOrder  OrdersCount
-----------------  -----------
1                  2
2                  1

也就是说,2个订单(OrdersCount)有1个客户(CustomersPerOrder),1个订单(OrdersCount)有2个客户(CustomersPerOrder)。

2 个答案:

答案 0 :(得分:2)

SELECT CustomersPerOrder, COUNT(*)
FROM
(
SELECT COUNT(*) as CustomersPerOrder
from CustomerOrder
group by CustomerOrder.OrderId
) sub
GROUP BY CustomersPerOrder

答案 1 :(得分:2)

收起不同并计算CustomersPerOrder

的出现次数
with counter as (
 select count(customerid) as CustomersPerOrder
 from CustomerOrder
 group by CustomerOrder.OrderId
)
select CustomersPerOrder, COUNT(*) as OrdersCount 
from counter
group by CustomersPerOrder