SQL-按组分组属性?

时间:2019-04-04 13:19:36

标签: sql group-by count

我有一张寄售表格(当然是简化的)

CONSIGNMENT_NR    CUSTOMER
1                 1
2                 1
3                 2
4                 2
5                 2

我可以轻松地为每个客户选择他们有多少托运货物:

SELECT CUSTOMER, COUNT(*) AS 'Count'
FROM CONSIGNMENT
GROUP BY CUSTOMER

谁会给我(带有示例数据)

CUSTOMER   Count
1          2
2          3

但是我想要获得的客户数量是x托运的数量。 我想要的数据如下所示:

Amount     No of Customers
2          1
3          1

我不太清楚怎么做。

2 个答案:

答案 0 :(得分:3)

将查询打包为派生表。 GROUP BY其结果:

select Amount, count(*) as No_of_Customers
from
(
    SELECT COUNT(*) AS Amount
    FROM CONSIGNMENT
    GROUP BY CUSTOMER
) dt
group by Amount

答案 1 :(得分:1)

您可以在下面尝试-使用子查询

select count(distinct customer) as noofcustomer, 'Count'
from
(
SELECT CUSTOMER, COUNT(*) AS 'Count'
FROM CONSIGNMENT
GROUP BY CUSTOMER
)A group by 'Count'