[英]Distinct SUM with Mysql Count
I have a query: 我有一个查询:
SELECT
t1.name as Name
count ( distinct t2.key ) as Total
SUM ( IF( t2.time = '12:00' , 1 , 0) ) as QttMidDay
FROM t1
LEFT JOIN t2 on t1.key = t2.key
GROUP BY t1.key
The question is, how i do the "Conditional Count" on the 2º parameter SUM for QttMidDay ? 问题是,我如何在QttMidDay的2º参数SUM上进行“有条件计数”?
I am guessing that you can solve your problem by aggregating before the join. 我猜想您可以通过在加入之前进行汇总来解决您的问题。 My best guess is: 我最好的猜测是:
SELECT t1.name as Name, t2.Total, t2.QttMidDay
FROM t1 LEFT JOIN
(SELECT COUNT(DISTINCT t2.key) as Total,
SUM(t2.time = '12:00') as QttMidDay
FROM t2
GROUP BY t2.key
) t2
ON t1.key = t2.key;
I am not sure if the COUNT(DISTINCT)
is necessary in the subquery. 我不确定子查询中是否需要COUNT(DISTINCT)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.