SELECT Category, SUM (Volume) as Volume
FROM Product
GROUP BY Category;
以上查询返回此结果:
Category Volume
-------------------
Oth 2
Tv Kids 4
{null} 1
Humour 3
Tv 5
Theatrical 13
Doc 6
我想将一些列组合为一个列,如下所示:
所以我的结果如下:
Category Volume
-------------------
Others 12
Tv 9
Film 13
我该怎么做?
答案 0 :(得分:3)
你需要一个CASE,就像这样:
SELECT
CASE
WHEN Category IN ('Oth','Humour','Doc')
OR Category IS NULL THEN 'Others'
WHEN Category IN ('Tv Kids','Tv') THEN 'TV'
WHEN Category = 'Theatrical' THEN 'Film'
END as category ,
SUM (Volume) as Volume
from Product
GROUP BY
CASE
WHEN Category IN ('Oth','Humour','Doc')
OR Category IS NULL THEN 'Others'
WHEN Category IN ('Tv Kids','Tv') THEN 'TV'
WHEN Category = 'Theatrical' THEN 'Film'
END;
Null必须在IN
列表之外处理,因为它是一个特殊值。
答案 1 :(得分:2)
我认为您需要使用case
语句将类别组合在一起。
select case category when 'Tv' then 'Tv'
when 'Film' then 'Film'
else 'Other'
end as Category,
sum(Volume) as Volume
from (
SELECT Category, SUM (Volume) as Volume
FROM Product
GROUP BY Category
) subcategoryTotals
group by Category
(我认为大多数数据库允许您按别名Category
分组。(如果不能,您可以重复使用案例陈述)
编辑:最后的想法(或两个):
您应该考虑规范化数据库 - 例如,Category
列应该是Categories
表的外键。
此外,这个sql相当合适,因为case
语句不会太长或太复杂。如果你想进一步分解,很快就会变得无法管理。我倾向于在我的数据库中使用类别和子类别的想法。
答案 2 :(得分:2)
最佳解决方案可能是在数据库中实现这些组。例如:
<强> category_group 强>
id_category_group name sortkey 1 Others 3 2 TV 2 3 Film 1
<强>类别强>
id_category name id_category_group 1 Oth 1 2 Tv Kids 2 3 Humour 1 4 Tv 2 5 Theatrical 3 6 Doc 1
<强>查询强>
SELECT g.Name, SUM (p.Volume) as Volume
FROM Product p
LEFT JOIN Category c ON c.Id_Category = p.Id_Category
LEFT JOIN Category_Group g ON g.Id_Category_Group = c.Id_Category_Group
GROUP BY g.Id_Category_Group, g.Name
ORDER BY g.sortkey;
然而,这使得NULL成为它自己的一组。但是,它是它自己的一组,因为NULL意味着尚未知道,所以你实际上并不知道它是电视,电影还是其他。如果您仍想将NULL计为其他,请相应地更改ON子句:
LEFT JOIN Category_Group g
ON g.Id_Category_Group = COALESCE(c.Id_Category_Group, 3) -- default to group 'Others'
答案 3 :(得分:1)
尝试以下,
select category_group , sum(volume) as Volume from
(
SELECT
Category,
Volume,
case
WHEN Category IN ('Oth','Humour','Doc','{null}') THEN 'Others'
WHEN Category IN ('Tv Kids','Tv') THEN 'TV'
WHEN Category = 'Theatrical' THEN 'Film'
end as category_group
FROM Product
) T
group by category_group