我正在尝试在我的以下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)中正常工作 但是我也该如何添加客户端?
答案 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;
注意:
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