1

我想按类型(M 或 C)显示给定用户的百分比,我尝试使用此查询:

SELECT TYPE,user_name,pourcentage_c,pourcentage_m,id_user, 
       COUNT(TYPE) AS crtitique ,COUNT(TYPE) AS majeur
FROM stat_alert  
LEFT OUTER JOIN user_qdf  ON user_qdf.`id` = id_user   
WHERE user_qdf.`id`=id_user AND TYPE='C'
GROUP BY id_user 
UNION ALL
SELECT TYPE,user_name,pourcentage_c,pourcentage_m,id_user,
       COUNT(TYPE) AS crtitique,COUNT(TYPE) AS majeur 
FROM stat_alert  
LEFT OUTER JOIN user_qdf  ON user_qdf.`id` = id_user   
WHERE user_qdf.`id`=id_user AND TYPE='M'
GROUP BY id_user

我想在同一行显示单个用户的关键和重要的百分比和数量

在此处输入图像描述

4

4 回答 4

2

您应该能够使用与此类似的东西(这基本上是一个PIVOT功能)。这会JOIN在您的user_qdf桌子上执行一次。然后,您应用带有语句的聚合函数来获取每个不同值CASE的计数(使用):SUMTYPE

SELECT TYPE, 
  user_name, 
  pourcentage_c, 
  pourcentage_m,
  id_user,
  sum(case when TYPE ='C' then 1 else 0 end) AS crtitique,
  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
于 2012-11-05T11:44:44.703 回答
0

这应该可以工作(现在无法测试)

SELECT TYPE,user_name,pourcentage_c,pourcentage_m,id_user,
    SUM(CASE user_qdf_c.TYPE WHEN 'C' 1 ELSE 0 END) AS crtitique,
    SUM(CASE user_qdf_m.TYPE WHEN 'M' 1 ELSE 0 END) AS majeur 
FROM stat_alert  
LEFT OUTER JOIN user_qdf user_qdf_c ON user_qdf_c.`id` = id_user AND TYPE='C'
LEFT OUTER JOIN user_qdf user_qdf_m ON user_qdf_m.`id` = id_user AND TYPE='M'
GROUP BY id_user

这个想法不是使用 COUNT,而是使用 SUM。

编辑这可以更好地重写,只使用一个左连接(这意味着更好的性能!)请参阅@SashiKant 和@bluefeet 的解决方案。

于 2012-11-05T11:39:42.360 回答
0

尝试这个::

  SELECT 
 TYPE,
user_name,pourcentage_c,pourcentage_m,id_user,COUNT(TYPE) AS crtitique ,COUNT(TYPE) AS majeur 

FROM stat_alert LEFT OUTER JOIN user_qdf ON user_qdf.id = id_user and user_qdf.id=id_user TYPE='C' or TYPE='M' GROUP BY id_user

于 2012-11-05T11:40:57.253 回答
0

尝试这个:

SELECT user_name, pourcentage_c, pourcentage_m, id_user,  
       COUNT(1) AS crtitique, COUNT(1) AS majeur
FROM stat_alert  
LEFT OUTER JOIN user_qdf ON user_qdf.id = id_user  
GROUP BY id_user, TYPE 
于 2012-11-05T12:01:48.007 回答