2014-05-04 65 views
0

好的,這裏的人是問題。 我必須列出每個部門的部門ID,部門名稱,銷售代表數量和平均佣金率。此外,我需要按部門分組,並按升序排列平均佣金率。SQL不是單組功能

我收到錯誤在De.Dept_ID下1行說是不是一個組由表達

這是我的代碼:

SELECT DE.Dept_ID as DeptID, Dept_Name as DeptName, COUNT(SR.Sales_Rep_ID) as SalesRepCount, 
Comm_Rate as AvgCommRate 
FROM DEPT_arb DE, SALES_REP_arb SR, COMMISSION_arb C 
WHERE DE.Dept_ID = SR.Dept_ID AND 
Comm_Rate = (SELECT AVG(Comm_Rate) FROM COMMISSION_arb WHERE SR.Comm_Class = C.Comm_Class) 
GROUP BY Dept_Name 
ORDER BY C.Comm_Rate; 

我欣賞的輸入

+1

你需要的,如果你調用任何聚合函數使用GROUP BY子句。 – OldProgrammer

+0

當我在Dept_Name上執行GROUP BY時,出現「未正確結束的組」錯誤。是的,我在它後面有一個分號。 – user2981579

+0

您可以編輯問題以擁有「GROUP BY」嗎?你是否將GROUP BY DE.Dept_ID視爲Dept_ID,Dept_Name'?另外,'AVG(Comm_Rate)AS AVGCOM'? – shahkalpesh

回答

0
SELECT DE.Dept_ID as Dept_ID, 
     Dept_Name, 
     COUNT(SR.Sales_Rep_ID) as NumOfSalesR, 
     AVG(Comm_Rate) as AVGCOM 
FROM DEPT_arb DE, SALES_REP_arb SR, COMMISSION_arb C 
WHERE DE.Dept_ID = SR.Dept_ID 
GROUP BY E.Dept_ID, 
     Dept_Name, 
ORDER BY C.Comm_Rate; 

您也可以考慮正確加入表格,例如:

SELECT DE.Dept_ID as Dept_ID, 
     Dept_Name, 
     COUNT(SR.Sales_Rep_ID) as NumOfSalesR, 
     AVG(Comm_Rate) as AVGCOM 
FROM DEPT_arb DE 
JOIN SALES_REP_arb SR on DE.Dept_ID = SR.Dept_Id 
JOIN COMMISION_arb C on SR.Comm_Class = C.Comm_Class 
GROUP BY E.Dept_ID, 
     Dept_Name, 
ORDER BY C.Comm_Rate; 
0

添加一個羣組。

SELECT DE.Dept_ID as Dept_ID, Dept_Name, 
    COUNT(SR.Sales_Rep_ID) as NumOfSalesR, 
    Comm_Rate as AVGCOM 
FROM DEPT_arb DE, SALES_REP_arb SR, COMMISSION_arb C 
WHERE DE.Dept_ID = SR.Dept_ID 
    AND Comm_Rate = (SELECT AVG(Comm_Rate) 
        FROM COMMISSION_arb 
        WHERE SR.Comm_Class = C.Comm_Class) 
GROUP BY DE.Dept_ID, Dept_Name, Comm_Rate 
0

改寫這種方式,看看它給你你想要的...

SELECT d.Dept_ID, d.Dept_Name, 
    Count(r.Sales_Rep_ID) NumOfSalesR, 
    c.Comm_Rate AVGCOM 
FROM DEPT_arb d, 
    Join SALES_REP_arb r 
     On r.Dept_ID = d.Dept_ID 
    Join COMMISSION_arb c 
     On c.Comm_Class = r.Comm_Class 
Group By d.Dept_ID, d.Dept_Name, c.Comm_Rate 
Where c.Comm_Rate = 
     (Select AVG(Comm_Rate) 
     From COMMISSION_arb 
     Where Comm_Class = r.Comm_Class) 
Order By c.Comm_Rate;