2

表结构如下:

Table1 (ID int, value1 int,...)

ID       Value1
----    --------
1        10
2        20
5        12


Table2 (ID int, value2 int,...)

ID       Value2
----    --------
1        13
3        24
4        11


Table3 (ID int, value3 int,...)
ID       Value3
----    --------
4        150
5        100

我的预期输出如下。

ID       Value1        Value2        Value3
----    --------      --------      --------
1         10            13             NULL
2         20            NULL           NULL
3         NULL          24             NULL
4         NULL          11             150
5         12            NULL           100

应该注意的是,上面的表格很大,我希望有最好的表现。

我的查询建议如下:

Select ID, 
       SUM(Value1) AS Value1, 
       SUM(Value2) AS Value2,
       SUM(Value3) AS Value3 
From (
    Select ID, Value1 , NULL as value2, NULL as value 3
    From Table1

    Union ALL

    Select ID, NULL , value2, NULL
    From Table2

    Union ALL

    Select ID, NULL, NULL, value 3
    From Table3
    )Z
Group By Z.ID
4

2 回答 2

3

假设每个 id 只有一个值,这应该可以解决问题:

SELECT aux.ID, t1.Value1, t2.Value2, t3.Value3
FROM 
(SELECT ID FROM Table1
 UNION
 select ID FROM Table2
 UNION
 SELECT ID FROM Table3) aux
LEFT OUTER JOIN Table1 t1 ON aux.ID = t1.ID
LEFT OUTER JOIN Table2 t2 ON aux.ID = t2.ID
LEFT OUTER JOIN Table3 t3 ON aux.ID = t3.ID

如果您有多个值:

SELECT aux.ID, SUM(t1.Value1) as 'Value1', SUM(t2.Value2) as 'Value2', SUM(t3.Value3) as 'Value3'
FROM 
(SELECT ID FROM Table1
 UNION
 select ID FROM Table2
 UNION
 SELECT ID FROM Table3) aux
LEFT OUTER JOIN Table1 t1 ON aux.ID = t1.ID
LEFT OUTER JOIN Table2 t2 ON aux.ID = t2.ID
LEFT OUTER JOIN Table3 t3 ON aux.ID = t3.ID
GROUP BY aux.ID
于 2012-06-11T10:45:49.450 回答
0

我最初写了与 aF 相同的答案。上面做了。所以,删除它,并使用不同的方法。

这里,

  • 第一个查询从 table1 中获取所有信息
  • 第二个查询从 table2 跳过中获取所有信息
  • 那些已经存在于 table1 3rd 查询中的所有剩余都跳过了上述两个查询中的那些。
  SELECT T1.ID, T1.VALUE1, T2.VALUE2, T3.VALUE3 --all T1
  FROM TABLE1 T1
      LEFT JOIN TABLE2 ON T1.ID=T2.ID
      LEFT JOIN TABLE3 ON T1.ID=T3.ID
UNION
  SELECT T2.ID, T1.VALUE1, T2.VALUE2, T3.VALUE3 --all T2 where T1 is NULL
  FROM TABLE1 T2
      LEFT JOIN TABLE1 ON T2.ID=T1.ID
      LEFT JOIN TABLE3 ON T2.ID=T3.ID
  WHERE T1.ID IS NULL
UNION
  SELECT T3.ID, T1.VALUE1, T2.VALUE2, T3.VALUE3 --all T3 where T1 is NULL AND T2 IS NUL
  FROM TABLE1 T3
      LEFT JOIN TABLE1 ON T3.ID=T1.ID
      LEFT JOIN TABLE2 ON T3.ID=T2.ID
  WHERE T1.ID IS NULL
        AND T2.ID IS NULL
于 2012-06-11T11:02:10.330 回答