SQL不是单个组组功能

时间:2014-05-04 19:26:29

标签: sql sqlplus

好的家伙在这里是个问题。 我必须列出每个部门的部门ID,部门名称,销售代表数量和平均佣金率。此外,我需要按部门分组,并按平均佣金率按升序排序。

我在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;

我很欣赏输入

3 个答案:

答案 0 :(得分: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; 

答案 1 :(得分: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

答案 2 :(得分: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;