2017-02-17 75 views
0

我有一個查詢:與MySQL鮮明SUM數

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 

的問題是,我該怎麼做就2º參數總和QttMidDay「條件計數」?

+0

OT:由於您選擇了t1.name,而是使用了GROUP BY列。 – jarlh

+2

添加一些示例表格數據和預期的結果 - 都是格式化文本。 – jarlh

回答

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)是必要的,子查詢。