2015-10-20 80 views
1

當我嘗試執行此查詢:查詢SQL服務器 - 「不包含在聚合函數或GROUP BY子句」

SELECT 
    EventNo, Customer.CustNo, CustName,EstCost, 
    SUM(EstCost) AS TotalEstCost, COUNT(*) 
FROM 
    EventRequest 
INNER JOIN 
    Customer ON EventRequest.CustNo = Customer.CustNo 
WHERE 
    Status = 'Approved' 
GROUP BY 
    Customer.CustNo; 

我得到這個錯誤:

Column 'EventRequest.EventNo' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

的表連接在這裏

enter image description here

回答

4

您可能需要GROUP BY一個ll字段不包含在聚合函數中。

SELECT EventNo, c.CustNo, CustName, EstCost, SUM(EstCost) AS TotalEstCost, COUNT(*) 
FROM EventRequest er 
INNER JOIN Customer c ON er.CustNo = c.CustNo 
WHERE Status = 'Approved' 
GROUP BY c.CustNo, EventNo, CustName, EstCost 

或者使用子查詢來選擇它們。

SELECT (SELECT ers.EventNo 
     FROM EventRequest ers 
     WHERE er.EventNo = ers.EventNo and ers.CustNo = c.CustNo) AS EventNo, 
     c.CustNo, 
     (SELECT cs.CustName 
     FROM Customer cs 
     WHERE c.CustName = cs.CustName AND c.CustNo = cs.CustNo) AS CustName, 
     (SELECT ers2.EstCost 
     FROM EventRequest ers2 
     WHERE er.EventNo = ers2.EventNo and ers2.CustNo = c.CustNo) AS EstCost, 
     SUM(EstCost) AS TotalEstCost, 
     COUNT(*) 
FROM EventRequest er 
INNER JOIN Customer c ON er.CustNo = c.CustNo 
WHERE Status = 'Approved' 
GROUP BY c.CustNo 
+0

感謝兩個方面,它如何可以解決 –

+0

@DraganSekuloski如果這個工作解釋,請勾選它作爲接受 – Matt

1

您必須添加的所有字段選擇語句將GROUP BY之後,你西港島線得到預期的結果。 例子:

SELECT EventNo, Customer.CustNo, CustName,EstCost, SUM(EstCost) AS TotalEstCost, COUNT(*) 
FROM EventRequest 
    INNER JOIN Customer ON EventRequest.CustNo = Customer.CustNo 
WHERE Status = 'Approved' 
GROUP BY EventNo, Customer.CustNo, CustName,EstCost; 
+0

很容易解釋的有效感謝 –

0

我懷疑你想客戶,而不是總被事件。因此,刪除無關列在描述事件的SELECT

SELECT c.CustNo, c.CustName, SUM(EstCost) AS TotalEstCost, COUNT(*) 
FROM EventRequest er INNER JOIN 
    Customer c 
    ON er.CustNo = c.CustN 
WHERE Status = 'Approved' 
GROUP BY c.CustNo, c.CustName; 

這將返回一行每客戶,事件和事件數量的成本一起。

2

當您使用GROUP BY子句時,只能使用聚合函數(MAX,SUM ...)選擇分組列或聚合非分組列。

在您的查詢,你被Customer.CustNo groupping,但你去選擇EventNo(及其他),這是造成錯誤。

您需要思考這個專欄,因爲選擇它是沒有意義的。如果您按客戶進行分組,則結果集將爲每位客戶設置一行(如果要合計某些客戶數據(如成本),這很有意義),但您希望如何輸出多個EventNo單行中的值?你可能不要想要它在那裏。 EstCost(不是總數)也是如此。

至於其他字段纔有意義(如CustName),你可以將它們添加到您的GROUP BY條款,那麼你可以直接選擇他們。

查詢更改爲:

SELECT Customer.CustNo, CustName, SUM(EstCost) AS TotalEstCost, COUNT(*) 
FROM EventRequest INNER JOIN Customer ON 
    EventRequest.CustNo = Customer.CustNo 
WHERE Status = 'Approved' 
GROUP BY Customer.CustNo, CustName; 
+0

問題,我試圖解決方法是:列出事件編號,客戶編號和客戶名稱,以及已批准事件的總估計成本。所有事件的總數是每個事件的估計成本的總和。按客戶編號分組結果。 –

+0

所以你想多行相同的總數? – Amit

相關問題