2014-03-07 78 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