2017-02-15 72 views
0

我使用此查詢的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」數據類型。我不知道如果這是問題。

+2

它是一個函數,但不是一個聚合函數,所以不是返回01/01/2017,而是返回一月份,但是您仍然可以擁有與另一個訂單月份相同的發佈者。你仍然需要將每個月分組在一起等,只需將月份(訂單日期)添加到你的組。如果你不想爲每個月和發佈商設置一個行,那麼你最好從完整的選擇中刪除它。 – MarkD

+0

月份函數不是一個聚合函數。集合函數的例子是Avg,Count,Max,Min,Sum等等。集合函數在多行上操作。月份功能只能在單行上操作。 –

+0

當你使用group by時,只有聚合函數被允許在不在組中的 – TheGameiswar

回答

0

由於錯誤狀態,您必須在分組列表中添加Orders.orderDate

+0

這會使錯誤消失,甚至可能是OP的意圖,但我們並不確定。 –

1
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, month(o.orderDate); 

這將返回

+-----+------+-------+-------+ 
| 1 |Bookco|January| 12 | 
| 1 |Bookco|Febuary| 6  | 
| 2 |NextBk|January| 2  | 
+-----+------+-------+-------+ 

沒有組由編譯器在訂單日期不知道如何處理各種個月現身爲每個發佈的。

0

如果我正確理解你,你會對簡單的標量函數和aggregate function感到困惑。聚合函數接受一組參數(來自多行的字段值)併產生一個結果,而簡單的標量函數產生每個參數所需的結果。在你的情況,一組

orderDate  quantity 
01/01/2017  2   
02/01/2017  2 
03/01/2017  2 

SELECT SUM(quantity) FROM table 

會產生只有一個值 - 6雖然

SELECT MONTH(orderDate) FROM table 

會產生價值的三行:

1 
2 
3 

這是簡單的標量的區別和聚合函數:聚合函數可以改變結果中的行數,而對於簡單函數,函數的輸入和輸出中將有相同數量的行。 因此,不能像聚合函數那樣接收每行的一個結果,因此必須將包含簡單函數的字段添加到GROUP BY子句中。

0

月不是一個聚合函數,則需要通過條款,包括你的團隊在此列:

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, month(o.orderDate); 
0

一些規則GROUP BY子句的:允許

  1. 唯一項目具有group by子句的查詢的選擇列表是

    • GROUP BY中的表達式
    • 聚合函數(SUM,COUNT,MAX,MIN,AVG)
  2. 表達式GROUP BY子句中不一定要包含在SELECT語句

正如已經被別人解釋的,月是不是一個聚合函數,但是一個標量函數。