我正在尝试编写一个SQL查询,它将输出多个变量,具体取决于数据库中特定数量的存在次数。然后,此信息将用于图表中。
数据库设置如下:
ID | quantity | etc..
---------------------
1 | 2 |
2 | 6 |
3 | 1 |
4 | 2 |
.
.
.
以下是我的查询:
SELECT
COUNT(CASE WHEN quantity = 1) AS quantity1,
COUNT(CASE WHEN quantity = 2) AS quantity2
FROM orders
但我希望它输出如下:
quantity1 | quantity2
---------------------
1 | 2 |
相反,我收到这些错误消息:
提前致谢!
编辑:如果你想在我的数据库上测试你的代码,链接就在下面......
-Link已删除 -
答案 0 :(得分:2)
这是另一种方法,也许有帮助:
SELECT SUM(CASE WHEN quantity = 1 THEN 1 ELSE 0 END) AS quantity_1,
SUM(CASE WHEN quantity = 2 THEN 1 ELSE 0 END) AS quantity_2,
SUM(CASE WHEN quantity = 3 THEN 1 ELSE 0 END) AS quantity_3,
SUM(CASE WHEN quantity = 4 THEN 1 ELSE 0 END) AS quantity_4,
SUM(CASE WHEN quantity = 5 THEN 1 ELSE 0 END) AS quantity_5,
SUM(CASE WHEN quantity = 6 THEN 1 ELSE 0 END) AS quantity_6,
SUM(CASE WHEN quantity > 6 THEN 1 ELSE 0 END) AS quantity_more_than_6
FROM orders
以下是MS Access的特殊查询:
SELECT SUM(SWITCH(quantity = 1, 1)) AS quantity_1,
SUM(SWITCH(quantity = 2, 1)) AS quantity_2,
SUM(SWITCH(quantity = 3, 1)) AS quantity_3,
SUM(SWITCH(quantity = 4, 1)) AS quantity_4,
SUM(SWITCH(quantity = 5, 1)) AS quantity_5,
SUM(SWITCH(quantity = 6, 1)) AS quantity_6,
SUM(SWITCH(quantity > 6, 1)) AS quantity_more_than_6
FROM orders
答案 1 :(得分:0)
使用GROUP BY子句,如:
SELECT quantity, COUNT(*) AS num
FROM Orders
GROUP BY quantity
HAVING COUNT(*) > 6;
编辑:你可以添加一个HAVING子句