SQL表合并

时间:2015-11-13 21:15:03

标签: sql sql-server

使用SQL Server 2008,我会尽力描述我想要做的事情。

假设我的表A看起来像这样:

表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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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