简体   繁体   English

使用 CASE 语句在 SQL 中分组

[英]Grouping in SQL using CASE Statements

Hello I am trying to group multiple customer orders into buckets in SQL, the output should look something like it does below.您好,我正在尝试将多个客户订单分组到 SQL 中的存储桶中,output 应该如下所示。 Do I have to use a case statement to group them?我是否必须使用案例陈述对它们进行分组?

Table1 looks like:表 1 看起来像:

CustomerID客户ID Order_date订购日期
1 1 somedate某日
2 2 somedate某日
3 3 somedate某日
2 2 somedate某日

Edit: # of customers meaning if CustomerID 2 had 2 orders he/she would be of the in the bucket of #of orders of 2.编辑:客户数量意味着如果 CustomerID 2 有 2 个订单,他/她将属于 #of order of 2。

Output should be something like this? Output 应该是这样的吧?

# of Customers # 客户 # of Orders订单数
2 2 1 1
1 1 2 2

My code so far is:到目前为止,我的代码是:

select count(*) CustomerID 
FROM Table1
GROUP BY CustomerID;

I believe what you want to do is get the count of orders by customer, first, via aggregation.我相信你想要做的是首先通过聚合获得客户的订单数量。 Then get the count of customers by order count from that query.然后通过该查询中的订单数获取客户数。

SELECT count(*) as count_of_customers, count_of_orders
FROM 
    (
        SELECT customerid, count(*) as count_of_orders
        FROM your_table
        GROUP BY customerid
    ) sub
GROUP BY count_of_orders
ORDER BY count_of_orders

Use a double aggregation:使用双重聚合:

SELECT COUNT(*) AS num_customers, cnt AS num_orders
FROM
(
    SELECT CustomerID, COUNT(*) AS cnt
    FROM Table1
    GROUP BY CustomerID
) t
GROUP BY cnt;

The inner subquery finds the number of orders for each customer.内部子查询查找每个客户的订单数量。 The outer query then aggregates by number of orders and finds out the number of customers having each number of orders.然后外部查询按订单数量聚合,并找出拥有每个订单数量的客户数量。

If you want to sort your tables and your users depending on the number of orders they made, this query should work:如果您想根据订单数量对表和用户进行排序,则此查询应该有效:

SELECT CustomerID, COUNT(CustomerID) as NbOrder 
FROM Table1 
GROUP BY(NbOrder)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM