通过查询sql分组

时间:2012-11-12 11:37:11

标签: php mysql sql

我想计算警报的数量和用户处理的警报数量,并键入type = C和M. 我从这个查询开始,它给了我主要和重要警报的数量,但是我被困在处理的警报数量

SELECT 
  TYPE,
  user_name,
  COUNT(type_alertes) AS nb, 
  id_user,
  SUM(CASE WHEN TYPE ='C' THEN 1 ELSE 0 END) AS critique,
  SUM(CASE WHEN TYPE ='M' THEN 1 ELSE 0 END) AS majeur 
FROM stat_alert  
 LEFT OUTER JOIN user_qdf ON user_qdf.`id` = id_user 
WHERE 
  user_qdf.`id`=id_user 
  AND TYPE IN ('M', 'C')
GROUP BY id_user 
谁能帮助我

1 个答案:

答案 0 :(得分:0)

如果您想要所有警报的数量,并且从那个C的数量和M的数量

SELECT 
  user_name,
  COUNT(type_alertes) AS nb, 
  id_user,
  SUM(CASE WHEN TYPE ='C' THEN 1 ELSE 0 END) AS critique,
  SUM(CASE WHEN TYPE ='M' THEN 1 ELSE 0 END) AS majeur 
FROM stat_alert  
 JOIN user_qdf ON user_qdf.`id` = id_user 
GROUP BY id_user, user_name 

应该这样做。 我假设user_name来自user_qdf表,而其他来自stat_alert,而id_user不是null。

编辑:警报总和

SELECT 
  user_name,
  COUNT(type_alertes) AS nb, 
  id_user,
  SUM(CASE WHEN TYPE ='C' THEN 1 ELSE 0 END) AS critique,
  SUM(CASE WHEN TYPE ='M' THEN 1 ELSE 0 END) AS majeur 
  SUM(CASE WHEN TYPE ='M' OR TYPE = 'C' THEN 1 ELSE 0 END) AS both_c_and_m
FROM stat_alert  
 JOIN user_qdf ON user_qdf.`id` = id_user 
GROUP BY id_user, user_name

EDIT2:

SELECT 
  user_name,
  COUNT(type_alertes) AS nb, 
  SUM(CASE WHEN TYPE ='C' THEN type_alertes ELSE 0 END) AS critique_alerts,
  SUM(CASE WHEN TYPE ='M' THEN type_alertes ELSE 0 END) AS majeur_alertes
  id_user,
  SUM(CASE WHEN TYPE ='C' THEN 1 ELSE 0 END) AS critique,
  SUM(CASE WHEN TYPE ='M' THEN 1 ELSE 0 END) AS majeur 
FROM stat_alert  
 JOIN user_qdf ON user_qdf.`id` = id_user 
WHERE TYPE in ('C','M')
GROUP BY id_user, user_name

是你想要的吗?