作者jonce007 (汪汪)
看板Database
標題Re: [SQL ] SQL新手問語法。
時間Fri Nov 1 09:30:14 2013
: 目前是用
: 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
感謝b大的回應
我的意思是,如果資料庫有100萬筆
用之前union的寫法,server 不就要算200萬筆?
第一次算完100萬筆後,如果得到3000筆,
希望只再算這3000筆做加總。
有 select count(*),sum(xx).. group by xx to temp t1 這種功能的語法嗎?(MYSQL)
^^^^^^^^^^^
如果有,之後就能寫成 t1 所有的row union t1 total的row
select * from temp table t1
union
selct count(*),sum(xx) from t1;
delete temp table t1;
如果不行或很複雜,考量server負擔,在local端計算再自行補上最後這筆total
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.43.36.53
※ 編輯: jonce007 來自: 114.43.36.53 (11/01 09:31)
→ bohei:嗯..mysql有TEMP TABLE,但我不確定有沒有你那種寫法 11/01 11:53
→ bohei:但照你這個寫法,也是要先GROUP BY 一次不是嗎 11/01 11:54
→ bohei:除非你這句SQL每次處理的資料都相同,不然你每遇到一次 11/01 11:56
→ bohei:就要重新INSERT TEMP一次,應該差不了多少吧? 11/01 11:56
→ jonce007:看來就client端自己加總吧..... 11/01 12:26
→ jonce007:感謝b大 11/01 12:27
→ bohei:唉呀呀 我只是推測XD 11/01 12:28