SQL组按多个类别

时间:2015-06-22 13:44:51

标签: php mysql sql mysqli

这是我用来计算每类预订的预订次数的查询。

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

2 个答案:

答案 0 :(得分:2)

只需为case表达式添加group by语句:

  SELECT (CASE WHEN Categories.name like 'Cat3%' THEN 'Cat3'
               ELSE Categories.name
          END) as name,
         sum(locations.name = 'loc 1' ) as Location1,
         sum(locations.name = 'loc 2') as Location2,
         sum(locations.name = 'loc 3') as Location3,
         count(*) as total
  FROM ...
  GROUP BY (CASE WHEN Categories.name like 'Cat3%' THEN 'Cat3'
                 ELSE Categories.name
            END)

答案 1 :(得分:0)

当然,只需添加更改群组定义即可将新名称合并为一个群组' ...

SELECT
   substring(Categories.name, 1, 4) CategoryName,
   count(case when locations.name ='loc 1' then 1 end) Location1,
   count(case when locations.name ='loc 2' then 1 end) Location2,
   count(case when locations.name ='loc 3' then 1 end) Location3,
   count(Categories.name) total,

FROM
  ...

group by substring(Categories.name, 1, 4)
with rollup