2013-02-11 64 views
0

查詢:包括求和行與GROUP BY子句

SELECT aType, SUM(Earnings - Expenses) "Rev" 
FROM aTable 
GROUP BY aType 
ORDER BY aType ASC 

結果:

| aType | Rev | 
| ----- | ----- | 
| A  | 20 | 
| B  | 150 | 
| C  | 250 | 

問: 是否有可能在底部顯示一個摘要行如下面通過在我的初始查詢中使用Sybase語法,或者它必須完全是一個單獨的查詢?

| aType | Rev | 
| ----- | ----- | 
| A  | 20 | 
| B  | 150 | 
| C  | 250 | 
================= 
| All | 320 | 

我無法從SQL彙總功能,成功地轉換過來的Sybase,但我不知道是否有另一種方式來做到這一點,如果在所有。

謝謝!

+1

'GROUP BY ROLLUP(aType)'應該在Sybase中工作 – 2013-02-11 22:56:59

+0

感謝rs。我收到錯誤:「Function'ROLLUP'not found。如果這是一個SQLJ函數或SQL函數,請使用sp_help ...」 – 2013-02-11 23:01:02

+0

@Matt。 。 。什麼版本的Sybase? – 2013-02-12 01:45:33

回答

1

您是否嘗試過只使用一個UNION ALL相似這個:

select aType, Rev 
from 
(
    SELECT aType, SUM(Earnings - Expenses) "Rev", 0 SortOrder 
    FROM aTable 
    GROUP BY aType 
    UNION ALL 
    SELECT 'All', SUM(Earnings - Expenses) "Rev", 1 SortOrder 
    FROM aTable 
) src 
ORDER BY SortOrder, aType 

請參閱SQL Fiddle with Demo。這給出了結果:

| ATYPE | REV | 
--------------- 
|  A | 10 | 
|  B | 150 | 
|  C | 250 | 
| All | 410 | 
+0

謝謝,這個解決方案工作完美。 – 2013-02-13 03:32:15

+0

@Matt樂意幫忙。 :) – Taryn 2013-02-13 10:22:21

1

並非所有版本的Sybase都支持ROLLUP。你可以用老式的方式做到這一點:

with t as 
    (SELECT aType, SUM(Earnings - Expenses) "Rev" 
    FROM aTable 
    GROUP BY aType 
    ) 
select t.* 
from ((select aType, rev from t) union all 
     (select NULL, sum(rev)) 
    ) t 
ORDER BY (case when atype is NULL then 1 else 0 end), aType ASC 

這是一種蠻橫的,蠻力的方法。如果此版本的Sybase不支持with,你可以這樣做:

select t.aType, t.Rev 
from ((SELECT aType, SUM(Earnings - Expenses) "Rev" 
     FROM aTable 
     GROUP BY aType 
    ) union all 
     (select NULL, sum(rev)) 
    ) t 
ORDER BY (case when atype is NULL then 1 else 0 end), aType ASC 

這是非常基本的,標準的SQL。

+0

即使附加,這仍然不起作用;在前面的例子是SQL(http://stackoverflow.com/questions/13357366/incorrect-syntax-near-the-keyword-table-when-i-declare-a-table-variable)。 此外,我試圖使用這個臨時表,仍然不好:/ – 2013-02-12 03:47:00

+1

@Matt。 。 。多麼令人沮喪。我的猜測是你的Sybase版本不支持'with'語句。 – 2013-02-12 14:12:59

+0

看起來這樣!管理控制也在我的手中,謝謝你的幫助,雖然隊友,讚賞。 – 2013-02-12 22:36:03

1

可能是你可以計算by子句中像SYBASE摸出:

create table #tmp1(name char(9), earning int , expense int) 
insert into #tmp1 values("A",30,20) 
insert into #tmp1 values("B",50,30) 
insert into #tmp1 values("C",60,30) 

select name, (earning-expense) resv from #tmp1 
group by name 
order by name,resv 
compute sum(earning-expense) 

OR

select name, convert(varchar(15),(earning-expense)) resv from #tmp1 
group by name 
union all 
SELECT "------------------","-----" 
union all 
select "ALL",convert(varchar(15),sum(earning-expense)) from #tmp1 

感謝, 戈帕爾