MySQL CASE COUNT查询并添加另一列

时间:2018-07-20 12:12:23

标签: mysql sql

我正在尝试在我的以下MySQL查询中添加一列(客户):

我的桌子

CLIENT  SEVERITYLEVEL TOTAL
  Bob        4        27
  Bob        3        24
  Bob        7        19
  Bob        5        10
  Bob        8        9
  Bob        6        7
  Bob        1        5
  Bob        2        3
  Gin        2        6
  Gin        3        7

我想要的输出

CLIENT SEVERITYLEVEL  Total

Bob    Severe         63
Bob    Moderate       32
Bob    Critical       9

...

select 
(case when (`s2`.`SEVERITYLEVEL` = 1) then 'Moderate' 
 when (`s2`.`SEVERITYLEVEL` = 2) then 'Moderate' 
 when (`s2`.`SEVERITYLEVEL` = 3) then 'Moderate' 
 when (`s2`.`SEVERITYLEVEL` = 4) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 5) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 6) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 7) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 8) then 'Critical' 
 when (`s2`.`SEVERITYLEVEL` = 9) then 'Critical' 
 when (`s2`.`SEVERITYLEVEL` = 10) then 'Critical' 
 when (`s2`.`SEVERITYLEVEL` = 10) then 'Critical' end) 
 AS `SEVERITYLEVEL`,count(0) AS `total` 

 from `s2` 
 group by (case when (`s2`.`SEVERITYLEVEL` = 1) then 'Moderate' 
 when (`s2`.`SEVERITYLEVEL` = 2) then 'Moderate' 
 when (`s2`.`SEVERITYLEVEL` = 3) then 'Moderate' 
 when (`s2`.`SEVERITYLEVEL` = 4) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 5) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 6) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 7) then 'Severe' 
 when (`s2`.`SEVERITYLEVEL` = 8) then 'Critical' 
 when (`s2`.`SEVERITYLEVEL` = 9) then 'Critical' 
 when (`s2`.`SEVERITYLEVEL` = 10) then 'Critical' end) 
 order by count(0) desc limit 10

我让表格在第二列/第三列(SEVERITY LEVEL + TOTAL)中正常工作 但是我也该如何添加客户端?

2 个答案:

答案 0 :(得分:1)

您需要添加name。该查询可以简化为:

select name,
      (case when s2.SEVERITYLEVEL in (1, 2, 3) then 'Moderate' 
            when s2.SEVERITYLEVEL in (4, 5, 6, 7) then 'Severe' 
            when s2.SEVERITYLEVEL in (8, 9, 10) then 'Severe' 
       end) as severity,
      count(*) as total 
from s2
group by name, severity
order by count(*) desc
limit 10;

注意:

  • MySQL使您可以在group by中使用别名。这很方便。
  • 给新列名一个新名称。一般来说,这只是保持明确的好建议。
  • 多余的引号只会使查询更难编写和阅读。没有伤害,但是为什么要打扰呢?
  • 我了解count(1),但count(0)似乎令人困惑,尤其是对于经验不足的人。 count(*)是用于计数行的SQL标准构造。

答案 1 :(得分:1)

我强烈建议将您的严重程度放在单独的表中。这样可以避免将来出现很多复杂性,并使许多查询的性能更高。

http://sqlfiddle.com/#!9/9f25cf/3

SELECT client, title, sum(total)
FROM s2 
LEFT JOIN severity
ON s2.severitylevel = severity.id
GROUP BY client, title