2014-03-02 57 views
2

我想通過post_author來計算平均結果。這裏是我的代碼:如何做條件平均?

AVG(CASE WHEN post_author = 1 THEN post_content ELSE 0 END)as avg 

它得到的100對2條結果(100,66.7),這應該是83.35 如果事情發生了錯誤?

+0

是post_auther和post_content數字列嗎? – Ray

+0

使用'group by post_author'進行'avg'計算時出了什麼問題? –

+1

考慮提供適當的DDL(和/或sqlfiddle)與期望的結果集合 – Strawberry

回答

4

你可以只下降了else條款,所以NULL在傳遞:

AVG(CASE WHEN post_author = 1 THEN post_content END) as "avg" 

您的查詢對於一般的用途不匹配的值設置爲0。你希望他們忽略,所以使用NULL

+0

AVG(CASE WHEN post_author = 1 THEN post_content ELSE NULL END),因爲avg可以使其更清楚 – georgecj11