0

我正在使用 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 |
+--------+---------------+

有人可以建议如何正确订购吗?

4

2 回答 2

1

您只需要

Order by NumOrders 

在您查询的最后

于 2019-02-04T15:12:02.967 回答
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 |
+--------+-------+
于 2019-02-04T16:15:17.797 回答