0
Table 1 

bln thn qty1    
1   2014    10  
1   2014    20  
2   2014    30  
3   2014    40  
2   2014    50  
4   2014    60  



Table 2

bln thn qty2    
3   2014    200 
5   2014    400 
2   2014    100 
2   2014    500 
4   2014    300 
6   2014    600 

New View

bln thn qty1    qty2
1   2014    30  0
2   2014    80  600
3   2014    40  200
4   2014    60  300
5   2014    0   400
6   2014    0   600

上部の 2 つのテーブルから、下部にテーブルのようなビューを作成したいと思います。

誰でも助けたいですか?:D ありがとう

4

2 に答える 2

1
--create a new view called newview
create view NewView as
--if table1 has a record for this bln use it; otherwise take table 2's value
select coalesce(t1.bln,t2.bln) bln
--same for thn
, coalesce(t1.thn,t2.thn) thn
--take the sum of qty1 calculated below (max used just because we need an aggregate - they're all the same
, max(t1.qty1) qty1
--same for qty2
, max(t2.qty2) qty2
--select from the tables summing the quantities here (so we have a 1:1 match on the join / don't have to sum for every match)
from (select bln, thn, sum(qty1) as qty1 from table1 group by bln, thn) t1
full outer join (select bln, thn, sum(qty2) as qty2  from table2 group by bln, thn) t2
    on t1.bln = t2.bln
    and t1.thn = t2.thn
--group by the common fields so we get 1 record per value combination
group by t1.bln, t2.bln, t1.thn, t2.thn 

SQLFiddle: http://sqlfiddle.com/#!6/708da/1

于 2014-09-30T08:24:21.803 に答える