[pgsql-jp: 32687] Re: unionの合計取得
Yoshihisa Inoue
bok @ bbsbrain.ne.jp
2004年 4月 6日 (火) 16:53:25 JST
ども井上です。
"Tadashi.Kanbayashi" <Tadashi.Kanbayashi @ toppan.co.jp> wrote:
> unionの結果を集計することは可能でしょうか。
> SQLその1:select a , sum(b) from tab1 where c=1 group by a;
> SQLその2:select a , sum(b) from tab1 where c=2 group by a;
> で,
> 1と2の合計値を算出したく。
> select ? , sum(?) from (SQLその1 union SQLその2);
> ?とsum(?)をどう書いたら,uninの合計値を取得できるでしょうか。
何をやりたいのかが良くわかりませんが一応書くと
select a,sum(sum_b)
from
(
select a as a,sum(b) as sum_b from tab1 where c = 1 group by a
union
select a as a,sum(b) as sum_b from tab1 where c = 2 group by a
) as union_data
group by a;
でいけると思うけど、
select a, sum(b) from tab1 where c = 1 or c = 2 group by a;
でも意味が同じで早いのでこっちのほうが良いと思われますが…
By Yoshihisa Inoue
pgsql-jp メーリングリストの案内