2013-01-02 69 views
0

目前我在做這個查詢:獲取「[錯誤] 1111 - 無效使用組功能的」錯誤

SELECT Date_Format(M.Signupdate,"%Y-%m") as YearMonth, 
SUM(IF(Count(H.Nr) >= 0,1,0)) , 
SUM(IF(Count(H.Nr) >= 1,1,0)) , 
SUM(IF(Count(H.Nr) >= 2,1,0)) , 
SUM(IF(Count(H.Nr) >= 3,1,0)) 
FROM people M 
INNER JOIN History H ON H.login = M.Login 
WHERE 
M.Masteraccount = "" AND 
M.logincount > 5 AND 
DATEDIFF(M.lastlogin,M.Signupdate) >= 3 AND 
DATEDIFF(H.EntryDate,M.Signupdate) <= 151 
GROUP BY YearMonth ORDER BY YearMonth ; 

不過,我不斷收到「[錯誤] 1111 - 無效使用組功能「錯誤。如果我刪除SUM的它工作得很好。有人請給我答案嗎?

回答

1

你不能在GROUP BY使用別名。您需要將Date_Format(M.Signupdate,"%Y-%m")放入GROUP BY才能使其正常工作。你也不能嵌套聚合函數,所以你需要使用一個子查詢來獲取count,然後使用sum

select YearMonth, 
    SUM(IF(CountNR >= 0,1,0)) , 
    SUM(IF(CountNR >= 1,1,0)) , 
    SUM(IF(CountNR >= 2,1,0)) , 
    SUM(IF(CountNR >= 3,1,0)) 
from 
(
    SELECT Date_Format(M.Signupdate,"%Y-%m") as YearMonth, 
     Count(H.Nr) CountNR 
    FROM people M 
    INNER JOIN History H 
     ON H.login = M.Login 
    WHERE M.Masteraccount = "" AND 
     M.logincount > 5 AND 
     DATEDIFF(M.lastlogin,M.Signupdate) >= 3 AND 
     DATEDIFF(H.EntryDate,M.Signupdate) <= 151 
    GROUP BY Date_Format(M.Signupdate,"%Y-%m") 
) src 
GROUP BY YearMonth 
ORDER BY YearMonth; 
+0

感謝您的快速反應!然而,這仍然查詢遞給我回同樣的錯誤:( –

+0

@VincentJames看到我的編輯,我錯過了嵌套聚集函數。再次感謝 – Taryn

+0

,但「DATEDIFF(H.EntryDate,M.Signupdate)<= 151」需要是在HAVING部分,因爲它使用另一個表,因此,不能在子查詢? –

相關問題