[英]MySQL CASE with COUNT query and adding another column
I'm trying to add a column (CLIENT) to my following MySQL query: 我正在尝试向以下MySQL查询添加列(CLIENT):
My table 我的桌子
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
My Desired Output 我想要的输出
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
I got the table working correctly for the 2nd/3rd column (SEVERITY LEVEL+TOTAL) but how can I add CLIENT as well ? 我的表在第二列/第三列(SEVERITY LEVEL + TOTAL)中正常工作,但是如何添加CLIENT?
You need to add the name
. 您需要添加name
。 The query can be simplified to: 该查询可以简化为:
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;
Notes: 笔记:
group by
. MySQL允许您在group by
使用别名。 This is a big convenience. 这是一个很大的方便。 count(1)
but count(0)
just seems confusing, especially for less experienced people. 我了解count(1)
但count(0)
似乎令人困惑,尤其是对于经验不足的人。 count(*)
is the SQL standard construct for counting rows. count(*)
是用于计数行的SQL标准构造。 I would strongly recommend to put your severities into separate table. 我强烈建议您将严重程度放在单独的表中。 That would help to avoid a lot of complexity in future and make many queries much more performant. 这将有助于避免将来的大量复杂性,并使许多查询的性能更高。
http://sqlfiddle.com/#!9/9f25cf/3 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.