让我说我有这张桌子
ID Item Number
1 Pork 10
2 Fish 15
3 Carrot 5
4 Tomato 5
我想按项目分组并将此组命名为“类别”,然后选择每个类别的数字总和,如下所示:
SELECT Sum(Number) AS Total,
FROM TABLE
GROUP BY IIF(Item IN ('Pork', 'Fish'), 'Meat', 'Vegetable')
但是如何获得我指定的类别名称?
答案 0 :(得分:1)
使用
SELECT
(CASE WHEN ITEM IN ('Pork', 'Fish') THEN 'Meat' ELSE 'Vegetable' END) TYPE, SUM(NUMBER)
FROM TABLE
GROUP BY (CASE WHEN ITEM IN ('Pork', 'Fish') THEN 'Meat' ELSE 'Vegetable' END)
答案 1 :(得分:1)
您也可以使用WITH
声明:
WITH T1 AS
(
SELECT IIF(Item IN ('Pork', 'Fish'), 'Meat', 'Vegetable') as Grp,
T.*
FROM T
)
SELECT Grp,SUM(Number) as Total
FROM T1
GROUP BY Grp