2015-11-13 56 views
2

使用SQL Server 2008,我會盡我所能來描述我想要做什麼。SQL表合併

比方說,我有一個看起來像這樣的表答:

表A

VarName | ValueA | ValueB 
----------------------------- 
var1  | 0.12 | 0.34 
var2  | 1.456 | 5.31 
var3  | 43  | 10 

而且,看起來像這樣的表B:

表B

VarName | ValueC | ValueD 
----------------------------- 
var1  | 0.03 | 0.04 
var2  | 2.01 | 2.87 
newvar | 55  | 50 

我想要做的就是把這些表結合起來,這樣最終結果就像這張表C.

表C

VarName | ValueA | ValueB | ValueC | ValueD 
--------------------------------------------------- 
var1  | 0.12 | 0.34 | 0.03 | 0.04 
var2  | 1.456 | 5.31 | 2.01 | 2.87 
var3  | 43  | 10 | 0  | 0 
newvar | 0  | 0  | 55 | 50 

注意,合併時,共同的行(VAR名)與值是不常見的列和變量在一個表中不存在更新,從其他表有其從另一個表中合併的列設置爲0,例如表B中的newvar和表A中的var3。

此請求是否有意義或需要進一步解釋?

+2

你嘗試過這麼遠嗎? – Sparky

+0

http://www.w3schools.com/sql/sql_join_full.asp似乎是你想要在這裏。 –

回答

1

你可以試試:

select VarName, max(ValueA), max(ValueB), max(ValueC), max(ValueD) from (
    select VarName, ValueA, ValueB, 0 as ValueC, 0 as ValueD 
    from TableA 
    union all 
    select VarName, 0, 0, ValueC, ValueD 
    from TableB 
) 
group by VarName 
0

如何:

SELECT 
    VarName 
    ,MAX(IValueA) AS ValueA 
    ,MAX(ValueB) AS ValueB 
    ,MAX(ValueC) AS ValueC 
    ,MAX(ValueD) AS ValueD 
FROM ( 
SELECT 
    VarName 
    ,ValueA 
    ,ValueB 
    ,0 AS ValueC 
    ,0 AS ValueD 
FROM A 
UNION ALL 
SELECT 
    VarName 
    ,0 AS ValueA 
    ,0 AS ValueB 
    ,ValueC 
    ,ValueD 
FROM B 
) a 
GROUP BY VarName