行和列的总和SQL

时间:2014-03-07 14:29:39

标签: sql sql-server-2008-r2 sql-server-2012

我有一张如下表格。

Year          AccountGroupA   AccountGroup B   RowSum
2004                 15                 23       38
2005                 10                 10       20
2006                  8                 15       23
2007                 16                 14       30
ColumnSum            49                 62      111

我需要大量的行和列ex: - 我在sql查询中需要结果为111。

结果需要从sql函数返回,因此理想情况下应该是单个查询。

3 个答案:

答案 0 :(得分:1)

这样的事情:

select year, 
       sum(accountGroupA) as accountGroupA, 
       sum(AccountGroupB)as accountGroupb, 
       sum(accountGroupA + AccountGroupB) as rowsum
from the_table
group by year with rollup 

这假设您每年只有一行,或者如果您有多个实际上想要按年分组的行。如果不是这种情况,您可以使用联合来实现相同的目标:

select year, accountGroupA, AccountGroupB, rowsum
from (
  select year, accountGroupA, AccountGroupB, accountGroupA + AccountGroupB as rowsum, 0 as union_order
  from the_table
  union all
  select null, sum(accountGroupA), sum(AccountGroupB), sum(accountGroupA + AccountGroupB), 1 
  from the_table
) t
order by union_order, year

SQLFiddle示例:http://sqlfiddle.com/#!6/bd4bc/2

答案 1 :(得分:0)

对于ColumnSum,SQL很简单:

SELECT sum(AccountGroupA), sum(AccountGroupB) from YOUR_TABLE

行总和必须像这样编码:

SELECT (AccountGroupA + AccountGroupB) as RowSum from YOUR_TABLE

忘记在一个SQL语句中获得所需的结果。虽然使用令人讨厌的嵌套SQL肯定是可行的,但我不推荐它。

答案 2 :(得分:0)

使用ROLLUP运算符。

MSDN参考:http://technet.microsoft.com/en-us/library/ms189305(v=sql.90).aspx

我在这里创建了一个SQL小提琴:http://sqlfiddle.com/#!6/df41d/7

更具体地说,代码在这里:

select 
   case when (Grouping(Year)) = 1 
         then 'ColumnSum' 
         else isnull(Year, 'Unknown') end as Year,
   sum(AccountGroupA) as AccountGroupA,
   sum(AccountGroupB) as AccountGroupB,
   sum(AccountGroupA + AccountGroupB) as RowSum
from TestTable
  group by Year with ROLLUP