SQL分组错误

时间:2012-10-08 10:10:05

标签: sql sql-server-2005

我正在运行以下SQL但仍然收到错误: -

  

'列'SRVS.dbo.BTQGLDistributionsWithProjectCodesHM.AccountNo'在选择列表中无效,因为它不包含在任何一个列表中   聚合函数或GROUP BY子句。

我正在运行的代码是: -

SELECT         AccountNo, 
           TransDate, 
           JournalNo, 
           AuditTrail, 
           Description, 
           JnlAmount, 
           ACTINDX, 
           CONTRACTNAME, 
           PAPROJNUMBER,GROUPING(PAPROJNUMBER) as PAPROJNUMBER, 
           SUM(PAFeebillamount) as total
FROM       SRVS.dbo.BTQGLDistributionsWithProjectCodesHM
GROUP BY   PAPROJNUMBER with rollup
ORDER BY   GROUPING (PAPROJNUMBER

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:2)

使用GROUP BY语句时,必须在group by子句中指定任何不使用聚合的内容。

SELECT     AccountNo,  
           TransDate,  
           JournalNo,  
           AuditTrail,  
           Description,  
           JnlAmount,  
           ACTINDX,  
           CONTRACTNAME,  
           PAPROJNUMBER,GROUPING(PAPROJNUMBER) as PAPROJNUMBER,  
           SUM(PAFeebillamount) as total 
FROM       SRVS.dbo.BTQGLDistributionsWithProjectCodesHM 
GROUP BY   
       AccountNo,  
       TransDate,  
       JournalNo,  
       AuditTrail,  
       Description,  
       JnlAmount,  
       ACTINDX,  
       CONTRACTNAME,
       PAPROJNUMBER with rollup 
ORDER BY   GROUPING (PAPROJNUMBER)

答案 1 :(得分:1)

您必须在SELECT语句中包含未包含在GROUP BY子句中的聚合函数中的所有列,如下所示:

SELECT AccountNo, TransDate, 
  JournalNo, AuditTrail, Description, 
  JnlAmount, ACTINDX, CONTRACTNAME, 
  PAPROJNUMBER, GROUPING(PAPROJNUMBER) as PAPROJNUMBER,
  SUM(PAFeebillamount) as total 
FROM SRVS.dbo.BTQGLDistributionsWithProjectCodesHM 
GROUP BY 
  AccountNo, TransDate, 
  JournalNo, AuditTrail, Description, 
  JnlAmount, ACTINDX, CONTRACTNAME, 
  PAPROJNUMBER
with rollup 
ORDER BY GROUPING (PAPROJNUMBER)