想將3個資料表合併為一個
3個資料表的欄位都相同 是由where條件不同而成
Table A
--------------
year id mea
100 001 10
100 002 20
99 006 15
99 007 21
98 008 10
Table B
---------------
year id mea
99 003 10
99 004 20
99 005 15
98 009 23
Table C
---------------
year id mea
98 010 12
想合併計算下面這個表單
count 為count(id) amea為SUM(mea)
Table ABC
----------------------------------------
A B C
year count amea count amea count amea
100 2 30 - - - -
99 2 36 3 45 - -
98 1 10 1 23 1 12
解法
將A、B、C表依年份進行GROUP,COUNT(id),SUM(mea),分別為TA、TB、TC
之後將TC併入TB併入TA再依年份排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | --建立測試資料表 CREATE TABLE A ( year nchar(10) NULL, id nchar(10) NULL, mea int NULL ) ON [PRIMARY] insert into A (year,id,mea) values ('100','001',10) insert into A (year,id,mea) values ('100','002',20) insert into A (year,id,mea) values ('99','006',15) insert into A (year,id,mea) values ('99','007',21) insert into A (year,id,mea) values ('98','008',10) CREATE TABLE B ( year nchar(10) NULL, id nchar(10) NULL, mea int NULL ) ON [PRIMARY] insert into B (year,id,mea) values ('99','003',10) insert into B (year,id,mea) values ('99','004',20) insert into B (year,id,mea) values ('99','005',15) insert into B (year,id,mea) values ('98','009',23) CREATE TABLE C ( year nchar(10) NULL, id nchar(10) NULL, mea int NULL ) ON [PRIMARY] insert into C (year,id,mea) values ('98','010',12) |
解法
將A、B、C表依年份進行GROUP,COUNT(id),SUM(mea),分別為TA、TB、TC
之後將TC併入TB併入TA再依年份排序
1 2 3 4 5 6 7 8 9 10 11 12 13 | select TA.*,TB.count,TB.amea,TC.count,TC.amea from ( select A.year,count(id) as count,sum(mea) as amea --group A from A group by A.year) as TA left outer join ( select B.year,count(id) as count,sum(mea) as amea --group B from B group by B.year) as TB ON TA.year = TB.year left outer join ( select C.year,count(id) as count,sum(mea) as amea --group C from C group by C.year) as TC ON TA.year = TC.year order by CONVERT(INT,TA.year) desc |
沒有留言:
張貼留言