2017-02-17 6 views
0

Ich habe eine Abfrage:Distinct SUM mit Mysql Count

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 

Die Frage ist, wie ich die "Conditional Count" zu tun auf dem 2e Parameter SUM für QttMidDay?

+0

OT: Da Sie t1.name wählen, GROUP BY stattdessen. – jarlh

+2

Fügen Sie einige Beispieltabellendaten und das erwartete Ergebnis hinzu - sowohl als formatierten Text. – jarlh

Antwort

0

Ich vermute, dass Sie Ihr Problem lösen können, indem Sie vor die Verbindung aggregieren. Meine beste Vermutung ist:

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; 

Ich bin nicht sicher, ob die COUNT(DISTINCT) in der Unterabfrage notwendig ist.