2014-03-06 60 views
0

我想從4個表中生成報告。無法弄清楚如何去做。 我正在使用sql server 2008 R2和asp.net作爲前端。如何從4個表中獲取值

[表1] ---> 2014

----------------------------- 
Division totalPrograms 
----------------------------- 
EDD-COA   3 
EDD-EDSD   2 
EDD-EOA   6 
EDD-SOA   2 
EDD-WOA   3 

表2 ----> 2013

------------------------------ 
Division totalPrograms 
------------------------------ 
EDD-COA   24 
EDD-EDSD    3 
EDD-EOA   14 
EDD-SOA   7 
EDD-WOA   11 

表3 ----> 2012

------------------------------ 
Division totalPrograms 
------------------------------ 
EDD-COA   12 
EDD-EDSD    1 
EDD-EOA   9 
EDD-SOA   7 
EDD-WOA   12 

表4 - - > 2011(注:本表中不存​​在EDD-SOA)

------------------------------- 
Division totalPrograms 
------------------------------- 
EDD-COA   2 
EDD-EDSD    1 
EDD-EOA   3 
EDD-WOA   3 

最終的結果應該是:>> ---->

--------------------------------------------- 
Division 2014 2013 2012 2011 
--------------------------------------------- 
EDD-COA 3 24 12 2 
EDD-EDSD 2 3 1 1 
EDD-EOA 6 14 9 3 
EDD-SOA  2  7  7  0 
EDD-WOA 3 11 12 3 

但我想爲EDD-SOA行的值作爲最終的表,但我米失去了一些東西。請指導我..

回答

0
SELECT a.Division as 'Division', 
(case when a.totalPrograms is null then '0' else a.totalPrograms 
end) '2014', 
(case when b.totalPrograms is null then '0' else b.totalPrograms 
end) '2013', 
(case when c.totalPrograms is null then '0' else c.totalPrograms 
end) '2012', 
(case when d.totalPrograms is null then '0' else d.totalPrograms 
end) '2011' 
from Table1 a FULL JOIN Table2 b 
ON a.Division = b.Division 
FULL JOIN Table3 c 
ON a.Division = c.Division AND b.Division = c.Division 
FULL JOIN Table4 d 
ON a.Division = d.Division AND b.Division = d.Division AND c.Division = d.Division 

輸出:

DIVISION 2014 2013 2012 2011 
EDD-COA  3 24 12 2 
EDD-EDSD 2 3 1 1 
EDD-EOA  6 14 9 3 
EDD-SOA  2 7 7 0 
EDD-WOA  3 11 12 3 
+0

越來越語法錯誤 – user2139057

+0

你有什麼錯誤? – Avt

+0

它正在工作,但我有改進的解決方案。你可以在這裏測試http://sqlfiddle.com/#!2/f01bf/3 – Avt