我使用此查詢的SQL如下:集團通過/集合錯誤 - SQL
SELECT p.publisherID, p.publisherName, month(o.orderDate), sum(ol.quantity)
FROM Orders o, orderLine ol, Publisher p, Book b
WHERE ol.orderNum = o.orderNum
And ol.isbn is not null
And b.isbn=ol.isbn
And p.publisherID=b.publisherID
Group By p.publisherID, p.publisherName;
我得到這個錯誤:
Msg 8120, Level 16, State 1, Line 1
Column 'Orders.orderDate' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
現在你可以看到,訂購日期列實際上是一個函數,但爲什麼我仍然會得到這個錯誤?我唯一能想到的是month()函數顯示(表達式datetime),當我將鼠標懸停在它上面時,orderDate只是一個「date」數據類型。我不知道如果這是問題。
它是一個函數,但不是一個聚合函數,所以不是返回01/01/2017,而是返回一月份,但是您仍然可以擁有與另一個訂單月份相同的發佈者。你仍然需要將每個月分組在一起等,只需將月份(訂單日期)添加到你的組。如果你不想爲每個月和發佈商設置一個行,那麼你最好從完整的選擇中刪除它。 – MarkD
月份函數不是一個聚合函數。集合函數的例子是Avg,Count,Max,Min,Sum等等。集合函數在多行上操作。月份功能只能在單行上操作。 –
當你使用group by時,只有聚合函數被允許在不在組中的 – TheGameiswar