我想按类型(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
我想在同一行显示单个用户的关键和重要的百分比和数量
答案 0 :(得分:2)
你应该可以使用类似的东西(这基本上是一个PIVOT
函数)。这会在JOIN
表上执行一次user_qdf
。然后,您应用带有CASE
语句的聚合函数来获取每个不同SUM
值的计数(使用TYPE
):
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
答案 1 :(得分: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。
编辑这可以更好地重写,仅使用一个LEFT JOIN(这意味着很多更好的性能!)请参阅@ SashiKant和@ bluefeet的解决方案。< / p>
答案 2 :(得分: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和user_qdf.id = id_user TYPE ='C'或TYPE ='M'GROUP BY id_user
答案 3 :(得分: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