2014-03-07 80 views
-3

我有一张如下表格。行和列的总和SQL

 
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 

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

结果需要从一个SQL函数返回,所以理想情况下应该是一个单一的查询。

+0

SQL Server 2012的 –

回答

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

0

对于ColumnSum的SQL很简单:

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

该行资金是编码这样的:

SELECT (AccountGroupA + AccountGroupB) as RowSum from YOUR_TABLE 

忘掉得到期望的结果在一个SQL statment。虽然这对于一个令人讨厌的嵌套SQL当然是可能的,但我不会推荐它。

+0

我需要返回这个结果从一个函数,所以我会bascially需要它作为一个单一的声明。 –

0

看看使用汇总操作。

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