sum列,显示每行的总数

时间:2014-01-16 16:15:47

标签: sql tsql sql-server-2005

我有一个如下所示的查询:

select Group, Sum(columnA) as SumColumn
FROM table
GROUP BY Group

我得到的结果看起来像这样

+-----+---------+
|Group|SumColumn|
+-----+---------+
|A    |10       |
+-----+---------+
|B    |20       |
+-----+---------+

如何更改/添加此内容以显示此类内容?

+-----+---------+-----------+
|Group|SumColumn|TotalColumn|
+-----+---------+-----------+
|A    |10       |30         |
+-----+---------+-----------+
|B    |20       |30         |
+-----+---------+-----------+

7 个答案:

答案 0 :(得分:6)

很难看出您的数据是什么样的 - 但是根据您发布的内容,这就是您想要的内容:

SELECT Name, 
       SumColumn,
       SUM(SumColumn) AS TotalColumn
FROM
(
    SELECT Group as Name, SUM(columnA) AS SumColumn
    FROM Table 
    GROUP BY Group
) T

你可能想要这个 - 取决于其他东西。

SELECT *,  
       SUM(columnA) OVER (PARTITION BY Group ORDER BY Group) AS SumColumn,
       SUM(columnA) OVER (PARTITION BY Group) AS TotalColumn
FROM TABLE

答案 1 :(得分:4)

使用子查询:

SELECT [Group], Sum(columnA) as SumColumn, 
       TotalColumn = (SELECT SUM(columnA) FROM dbo.Table1)
FROM dbo.Table1
GROUP BY [Group]

Demo

答案 2 :(得分:2)

您实际上可以在select语句中混合窗口函数和聚合函数。因此,您可以在没有子查询的情况下执行此操作:

select Group, Sum(columnA) as SumColumn,
       sum(sum(columnA)) over () as TotalColumns
FROM table
GROUP BY Group;

答案 3 :(得分:1)

虽然这可能不是最有效的方法。这是我的答案。

SELECT a.*,
    (select Sum(columnA)
     FROM table) as [TotalColumn]
FROM (select Group, Sum(columnA) as SumColumn
      FROM table
      GROUP BY Group) as a

答案 4 :(得分:1)

这很奇怪,您希望显示总列数和每行。运行总价值是我所期望的。但是如果你想这样它只是一个常数,你可以将Total SUM Value存储在变量中,然后在SLECT FROM TABLE查询中执行Select Variable。

    DECLARE @table TABLE
    (
        c1  sysname     NOT NULL
        ,c2 int         NOT NULL
    )
    INSERT INTO @table( c1, c2 )
    SELECT 'A',10 
    UNION ALL SELECT 'B',20 
    UNION ALL SELECT 'C',30

    DECLARE @tSum BIGINT
    SELECT @tSum = SUM(C2) FROM @table

    SELECT c1,c2,@tSum AS Tsum
    FROM @table

enter image description here

答案 5 :(得分:1)

你好,这对我有用

select a.id,a.val1,b.val2,e.s 
from tbl1 as a 
inner join ( select c1,sum(val1) as s from tbl2 group by c1) as e
    on a.c1=e.c1

答案 6 :(得分:0)

SELECT t.Group,t.SumColumn, 
       (SELECT SUM(a.SumColumn) 
          FROM Table a
         WHERE a.Group=t.Group) TotalColumn
FROM Table t