我正在使用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 |
+--------+---------------+
有人可以建议如何正确订购吗?
答案 0 :(得分:1)
您只需要
Order by NumOrders
在查询的最后
答案 1 :(得分: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 |
+--------+-------+