作者jonce007 (汪汪)
看板Database
標題[SQL ] SQL新手問語法。
時間Thu Oct 31 20:20:46 2013
table tb_a ( no, amt )
假設有十筆資料,no有三種。
select no, count(*), sum(amt) from tb_a group by no
得到
row 1: a 2 123
row 2: b 3 223
row 3: c 5 323
--------------------------------------------------------
如果我想加上第4行
row 4:合計 10 669
目前是用
select no, count(*) as tno , sum(amt) as tamt from tb_a group by no
union
select '合計' as no, count(*) as tno , sum(amt) as tamt from tb_a
但是這樣,server應該會跑兩次運算吧。
可以group完再group同時出現 row 1-4,而server端只運算一次嗎?
我試過subselect
select '合計' as no, sum(tno), sum(tamt) from
(select no, count(*) as tno , sum(amt) as tamt from tb_a group by no ) as t1
但這也只是我要的row 4, row 1-3不見了。
想不出來啊,請提示一下好嗎? 感恩。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.164.2.207
→ bohei:感覺無論如何都一定要兩次 10/31 23:33
→ bohei:第一次先group第二次才能去sum 10/31 23:34
推 wangks:寫stored procedure, 用cursor把紀錄丟到TempTable並累加 11/01 15:16