2013-12-11 110 views
1

我有一個SQL查詢,像這樣:聚合函數導致錯誤

SELECT Month(mimos.mimo_date) & "-" & Year(mimos.mimo_date) AS monthyear, 
     Sum(Iif(mimos.amount < 0, mimos.amount, 0))   AS debits, 
     Sum(Iif(mimos.amount > 0, mimos.amount, 0))   AS credits 
FROM mimos 
GROUP BY monthyear, 
      debits, 
      credits; 

這引發錯誤:

You tried to execute a query that does not include the specified expression ... as part of an aggregate function. (Error 3122)

我似乎無法儘管進行了廣泛的谷歌搜索來解決這個問題。有沒有人有解決方案?

+0

Iif是訪問中的東西? – Mihai

+0

它實際上是'iif'。美化大寫 – harryg

+1

考慮格式()'建立'monthyear' ...'格式(mimos.mimo_date,'mm-yyyy')AS monthyear' – HansUp

回答

3

試試這個方法:

SELECT Month(mimos.mimo_date) & "-" & Year(mimos.mimo_date) AS monthyear, 
     Sum(Iif(mimos.amount < 0, mimos.amount, 0))   AS debits, 
     Sum(Iif(mimos.amount > 0, mimos.amount, 0))   AS credits 
FROM mimos 
GROUP BY Month(mimos.mimo_date) & "-" & Year(mimos.mimo_date); 

僅在需要時不使用聚合函數來聚合。而且,您不能在別的查詢中使用別名作爲字段。

+0

這樣做的竅門!謝謝,10分鐘後會接受 – harryg

0

我認爲問題是別名還沒有作用域。一種方法是:

SELECT * 
FROM (
    SELECT Month(mimos.mimo_date) & "-" & Year(mimos.mimo_date) AS monthyear, 
     Sum(Iif(mimos.amount < 0, mimos.amount, 0))   AS debits, 
     Sum(Iif(mimos.amount > 0, mimos.amount, 0))   AS credits 
) q 
GROUP BY monthyear, 
      debits, 
      credits;