2015-10-06 92 views
2
當計一審

說我有如下表,只有同時使用DISTINCT和GROUP BY

timedate id 
    2015-01-01 1 
    2015-01-01 2 
    2015-01-01 3 
    2015-01-01 4 
    2015-01-02 1 
    2015-01-02 2 
    2015-01-02 5 
    2015-01-02 6 
    2015-01-03 2 
    2015-01-03 3 

這個查詢

SELECT 
     COUNT(DISTINCT `id`) as total, 
     timedate 
FROM Table1 
GROUP BY timedate 

產生以下結果

total timedate 
    4  2015-01-01 
    4  2015-01-02 
    2  2015-01-03 

因爲它計算每個組內不同的id

我該如何獲得每個不同ID的計數,而不在隨後的組中進行計數?例如像這樣的結果:

total timedate 
    4  2015-01-01 
    2  2015-01-02 
    0  2015-01-03 

回答

1

你最好在這裏使用兩個子查詢。一拿到id和它的min(timedate),另一個是得到不同timedates:

SELECT 
     COUNT(DISTINCT `id`) as total, 
     t1.timedate 
FROM 
    (SELECT DISTINCT TimeDate FROM Table1) as t1 
    LEFT OUTER JOIN (SELECT min(Timedate) as firsttimedate, id FROM Table1 GROUP BY id) as t2 ON 
     t1.timedate = t2.firsttimedate 
GROUP BY t1.timedate 
+0

這不會返回'0 2015-01-03'行。 –

+0

啊!是的。錯過了這個要求。更新! – JNevill