SQL SUM混乱

时间:2012-10-08 13:54:43

标签: sql sql-server-2005 sum

我为我的数据运行了以下查询: -

SELECT     CONTRACTNAME,
           AccountNo,
           TransDate, 
           JournalNo,
           AuditTrail,           
           Description,       
           CONTRACTNUMBER,
           GROUPING(CONTRACTNUMBER) as CONTRACTNUMBER,   
           SUM(PAFeebillamount)as Total  
FROM       SRVS.dbo.BTQGLDistributionsWithProjectCodesHM
WHERE      TransDate > '2012' AND CONTRACTNUMBER <> '00900'
GROUP BY   CONTRACTNAME,  
           AccountNo,   
           TransDate,
           JournalNo, 
           AuditTrail,    
           Description,      
           CONTRACTNUMBER with rollup  
ORDER BY   GROUPING (CONTRACTNUMBER) 

这给了我结果: -

enter image description here

如何更改此设置,以便为每个合同编号获得一行总计。所以它看起来像下面的例子: -

enter image description here

在这个时刻,我并没有因为没有/期刊没有等问题而烦恼,因为它只是一个总结。

只是寻找有关按合约编号总结我的团队的最佳方法的建议?

3 个答案:

答案 0 :(得分:1)

SELECT CONTRACTNAME, CONTRACTNUMBER, grouping(CONTRACTNUMBER) as CONTRACTNUMBER
SUM(PAFeebillamount)as Total
FROM SRVS.dbo.BTQGLDistributionsWithProjectCodesHM 
WHERE TransDate > '2012' AND CONTRACTNUMBER <> '00900' 
GROUP BY 
  CONTRACTNAME,
  CONTRACTNUMBER with rollup
ORDER BY GROUPING (CONTRACTNUMBER)

这应该为您提供每份合约的总额。获得多个结果的原因是因为您要对contractName,Acct,Date,JournalNo,AuditTrail和Desc进行分组。如果您想要一个完整的总数(每个合同号一个),那么您需要仅根据合同号进行分组。

答案 1 :(得分:1)

SELECT     CONTRACTNAME,
           '' AccountNo,
           '' TransDate, 
           '' JournalNo,
           '' AuditTrail,           
           '' Description,       
           CONTRACTNUMBER,
           GROUPING(CONTRACTNUMBER) as CONTRACTNUMBER,   
           SUM(PAFeebillamount)as Total  
FROM       SRVS.dbo.BTQGLDistributionsWithProjectCodesHM
WHERE      TransDate > '2012' AND CONTRACTNUMBER <> '00900'
GROUP BY   CONTRACTNAME,                  
           CONTRACTNUMBER with rollup  
ORDER BY   GROUPING (CONTRACTNUMBER) 

答案 2 :(得分:0)

由于您不打算为AccountNo, TransDate, etc选择什么,您可以使用MAX作为聚合函数,例如:

SELECT
  CONTRACTNAME, 
  MAX(AccountNo), 
  MAX(TransDate), 
  MAX(JournalNo),
  MAX(AuditTrail),
  MAX(Description),
  CONTRACTNUMBER, 
  GROUPING(CONTRACTNUMBER) as CONTRACTNUMBER, 
  SUM(PAFeebillamount)as Total
FROM SRVS.dbo.BTQGLDistributionsWithProjectCodesHM 
WHERE TransDate > '2012' 
  AND CONTRACTNUMBER <> '00900' 
GROUP BY 
  CONTRACTNAME,
  CONTRACTNUMBER with rollup
ORDER BY GROUPING (CONTRACTNUMBER)

如果您不想要它们,只需将其从SELECT声明中删除,或将其替换为NULL''

SELECT
  CONTRACTNAME,
  CONTRACTNUMBER, 
  GROUPING(CONTRACTNUMBER) as CONTRACTNUMBER, 
  SUM(PAFeebillamount)as Total
FROM SRVS.dbo.BTQGLDistributionsWithProjectCodesHM 
WHERE TransDate > '2012' 
  AND CONTRACTNUMBER <> '00900' 
GROUP BY 
  CONTRACTNAME,
  CONTRACTNUMBER with rollup
ORDER BY GROUPING (CONTRACTNUMBER)