2011-02-25 66 views
0

我當前的查詢如下:如何將HAVING和GROUP BY組合到同一個SQL中?

SELECT user_id, sum(...) as total from mytable 
group by user_id 

工作正常

然而,當我嘗試

SELECT user_id, sum(...) as total from mytable 
group by user_id 
having total >= 10 

我得到一個錯誤

SELECT user_id, sum(...) as total from mytable 
having total >= 10 

工作正常。我如何結合HAVING和GROUP BY?

+0

你會得到什麼錯誤?運行所有三個查詢都適用於我,我只是得到不同的結果集。 – BoltClock 2011-02-25 11:55:40

+0

'@deltanovember:'你使用哪個數據庫? – Wowa 2011-02-25 12:57:52

回答

3
SELECT user_id, sum(...) as total from mytable 
group by user_id 
having SUM(...) >= 10 
+0

不管是使用total還是sum(...)'... – BoltClock 2011-02-25 11:56:04

+0

不知道這是怎麼解決問題的! – rkg 2011-02-25 11:59:49

+1

'@BoltClock:'它依賴於數據庫。 mysql也有'total',而mssql沒有。 – Wowa 2011-02-25 12:56:40

0

HAVING與集合函數一起使用,而不是列。這就像where子句,但對於聚合。