与Mysql Count不同的SUM

时间:2017-02-17 12:27:57

标签: mysql sql doctrine

我有一个问题:

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

问题是,我如何对QttMidDay的2º参数SUM进行“条件计数”?

1 个答案:

答案 0 :(得分:0)

我猜您可以通过在加入之前聚合来解决您的问题。我最好的猜测是:

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;

我不确定子查询中是否需要COUNT(DISTINCT)