没能在MySQL命令列

问题描述 投票:0回答:2

我使用该表从Northwind数据集(可以从下面的查询来生成)

+-----------+-----------+
| NumOrders | CustCount |
+-----------+-----------+
|         1 |         1 |
|         2 |         2 |
|         3 |         7 |
|         4 |         6 |
|         5 |        10 |
|         6 |         8 |
|         7 |         7 |
|         8 |         4 |
|         9 |         5 |
|        10 |        11 |
|        11 |         4 |
|        12 |         3 |
|        13 |         3 |
|        14 |         6 |
|        15 |         3 |
|        17 |         1 |
|        18 |         3 |
|        19 |         2 |
|        28 |         1 |
|        30 |         1 |
|        31 |         1 |
+-----------+-----------+`

我想编写一个查询,提供X的人谁做订单y个数量的直方图

select 
    case 
        when NumOrders > 0 and NumOrders <= 5 then '0 - 5'
        when NumOrders > 5 and NumOrders <=10 then '6 - 10'
        else '10+' 
    end as Bucket,
    CustomerCount = sum(CustCount)
from (
    select 
        NumOrders,
        CustCount = count(*) 
    from (
        select * 
        from (
            select 
                CustomerID, 
                count(*) as NumOrders
            from orders 
            group by CustomerID
            ) c
        ) b
    group by NumOrders
    )a
group by 
(
    case 
        when NumOrders > 0 and NumOrders <= 5 then '0 - 5'
        when NumOrders > 5 and NumOrders <=10 then '6 - 10'
        else '10+' 
    end 
)

从上面的查询我得到这个输出,这是不正确排序。

+--------+---------------+
| Bucket | CustomerCount |
+--------+---------------+
| 0 - 5  |            26 |
| 10+    |            28 |
| 6 - 10 |            35 |
+--------+---------------+

我想它会在订购

+--------+---------------+
| Bucket | CustomerCount |
+--------+---------------+
| 0 - 5  |            26 |
| 6 - 10 |            35 |
| 10+    |            28 |
+--------+---------------+

有人建议如何正确排序呢?

mysql northwind ssms-2017
2个回答
1
投票

您只需要

Order by NumOrders 

在查询的最后


0
投票

我看不出这有什么失败的问题的一部分来解决...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(NumOrders SERIAL PRIMARY KEY
,CustCount INT NOT NULL
);

INSERT INTO my_table VALUES
(1 ,1),
(2 ,2),
(3 ,7),
(4 ,6),
(5 ,0),
(6 ,8),
(7 ,7),
(8 ,4),
(9 ,5),
(10,1),
(11,4),
(12,3),
(13,3),
(14,6),
(15,3),
(17,1),
(18,3),
(19,2),
(28,1),
(30,1),
(31,1);

SELECT CASE WHEN numorders BETWEEN 0 AND  5 THEN '0-5'
            WHEN numorders BETWEEN 6 AND 10 THEN '6-10'
            ELSE '+10' END bucket
      , COUNT(*) total
   FROM my_table
  GROUP
     BY bucket
  ORDER
     BY numorders;
+--------+-------+
| bucket | total |
+--------+-------+
| 0-5    |     5 |
| 6-10   |     5 |
| +10    |    11 |
+--------+-------+
© www.soinside.com 2019 - 2024. All rights reserved.