我该如何查询总和

时间:2018-06-20 03:37:45

标签: sql-server group-by sum

我有这样的查询

  SELECT a.code ,a.group ,a.Desc ,
         Sum(CONVERT(decimal(10,2),a.amount)) 'BYDESC'
    FROM table1 as a
   WHERE a.Bol = 'Y'
GROUP BY a.code,a.group,a.Desc
ORDER BY a.code 
         Asc ,a.group asc ,a.Desc asc

它给了我一张这样的桌子

CODE   GROUP  DESC        BYDESC
--------------------------------
G001   00001  D001          15.0
G001   00001  D002           3.0
G001   00001  D003         354.0
G001   00002  D001          27.0
   .       .     .             .
   .       .     .             .
   .       .     .             .
--------------------------------

我想对每个组进行求和并显示如下

CODE   GROUP  DESC        BYDESC  Sum(BYGROUP)
---------------------------------------------
G001   00001  D001          15.0        372.0
G001   00001  D002           3.0        372.0
G001   00001  D003         354.0        372.0
G001   00002  D001          27.0         27.0
   .       .     .             .            .
   .       .     .             .            . 
   .       .     .             .            .
----------------------------------------------

3 个答案:

答案 0 :(得分:2)

您可以使用公用表表达式来实现。
试试这个。

;with sumTable 
AS
( 
        SELECT a.code ,a.group ,Sum(CONVERT(decimal(10,2),a.amount)) SUMBYGROUP
          FROM table1 as a
          WHERE a.Bol = 'Y'
       GROUP BY a.code,a.group

)
  SELECT a.code ,a.group ,a.Desc ,Sum(CONVERT(decimal(10,2),a.amount)) 'BYDESC', sumTable.SUMBYGROUP as 'Sum(BYGROUP)'
    FROM table1 as a
    JOIN sumTable 
      ON (
          sumTable.code = a.code And sumTable.group = a.group 
         )
   WHERE a.Bol = 'Y'
GROUP BY a.code,a.group,a.Desc, sumTable.SUMBYGROUP
ORDER BY a.code asc ,a.group asc ,a.Desc asc

答案 1 :(得分:1)

;with GroupedTable 
AS
( 
    SELECT a.[COL1] ,a.[COL2] ,a.[COL3] ,Sum(CONVERT(decimal(10,2),a.[COL4])) 
     'BYDESC'
    FROM MyTable as a
    GROUP BY a.[COL1],a.[COL2],a.[COL3] 
)

SELECT 
    a.[COL1] ,a.[COL2] , a.[COL3] 
    ,Sum(CONVERT(decimal(10,2),a.[COL4])) 'BYDESC', mt.SUM
FROM MyTable as a
INNER JOIN 
(
   SELECT gt.[COL1] ,gt.[COL2] ,Sum(CONVERT(decimal(10,2),gt.[BYDESC])) AS 'SUM'
  FROM GroupedTable as gt
  GROUP BY gt.[COL1] ,gt.[COL2] 
) mt ON mt.[COL1] = a.[COL1] AND mt.[COL2] = a.[COL2]
GROUP BY a.[COL1],a.[COL2],a.[COL3], mt.SUM
ORDER BY  a.[COL1],a.[COL2],a.[COL3], mt.SUM

DB Fiddle

答案 2 :(得分:1)

u可以使用Windows函数来实现。

with cte as
   (SELECT a.code,
        a.group,
        a.Desc,
        Sum(CONVERT(decimal(10,2),a.amount)) 'BYDESC'
        FROM table1 as a
        WHERE a.Bol = 'Y'
        GROUP BY a.code,a.group,a.Desc
       ) 
select *, 
sum(bydesc) over (partition by [group] order by [desc]
 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
    from cte
ORDER BY code Asc ,[group] asc , [Desc] asc