这是我用来计算每个预订类别预订了多少个事件的查询。SQL Group按多个类别
SELECT
Categories.name,
count(case when locations.name ='loc 1' then 1 end) as Location1,
count(case when locations.name ='loc 2' then 1 end) as Location2,
count(case when locations.name ='loc 3' then 1 end) as Location3,
count(Categories.name) as total
FROM
...
group by Categories.name
with rollup
这给了我以下结果:
+------------------------------------------------------------+
|Category_name | Location1 | Location2 | Location3 | Total |
+------------------------------------------------------------+
|Cat1 | 1 | 2 | 2 | 5 |
|Cat2 | 2 | 1 | 2 | 5 |
|Cat3 | 2 | 2 | 2 | 6 |
|Cat3(Extra) | 1 | 3 | 2 | 6 |
|Cat4 | 3 | 1 | 2 | 6 |
+------------------------------------------------------------+
|Total per loc | 9 | 9 | 10 | 28 |
+------------------------------------------------------------+
这是令人满意的到现在为止! 现在我需要做同样的请求,但我想我需要通过(??)更改组。 有没有办法改变我的要求是:
Count for Cat1 the number of events per location.
Count for Cat2 the number of events per location.
Count for Cat3 and Cat3(extra) the number of events per location.
Count for Cat4 the number of events per location.
我的意思是某些类别需要算在一起,什么我期待实现的是这样的结果:
+------------------------------------------------------------+
|Category_name | Location1 | Location2 | Location3 | Total |
+------------------------------------------------------------+
|Cat1 | 1 | 2 | 2 | 5 |
|Cat2 | 2 | 1 | 2 | 5 |
|Cat3 | 3 | 5 | 4 | 12 |
|Cat4 | 3 | 1 | 2 | 6 |
+------------------------------------------------------------+
|Total per loc | 9 | 9 | 10 | 28 |
+------------------------------------------------------------+
莫非
你请帮我到那里。谢谢。 SB
不是最优的,但是一种方法是按类别名称的前4个字符进行分组,而不是完整的名称。像这样:http://stackoverflow.com/questions/666525/group-by-first-character – Maximus2012
谢谢。我更喜欢使用一个语句(CASE当Categories.name像'Cat3%'THEN'Cat3'ELSE Categories.name END)以避免类别名称过于相似时可能出现的错误。非常感谢您的意见。 –
当然。另一种方法(我认为可能有更好的性能和功能)可以为category_group创建一个整数列,将Cat3和Cat3(Extra)分配给相同的category_group,然后执行GROUP BY category_group。不知道在你的情况下,你允许多少表格修改。 – Maximus2012