0

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

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) 

这给了我结果:-

在此处输入图像描述

我怎样才能改变这个,所以我得到每个合同号的单行总计。所以它看起来像下面的例子: -

在此处输入图像描述

此时此刻,我并不在意帐户编号/期刊编号等,因为它只是一个摘要。

只是在寻找有关按合同编号总结我的组的最佳方法的建议?

4

3 回答 3

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 进行分组。如果您想要一个完整的总数(每个合同号一个),那么您需要仅对合同号进行分组。

于 2012-10-08T14:01:56.967 回答
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) 
于 2012-10-08T14:02:33.177 回答
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)

如果您不想要它们,只需将它们从语句中删除,或用orSELECT替换它们: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)
于 2012-10-08T14:02:32.557 回答