我想创建组合来自两个表的数据的视图,每个表中的样本数据如下所示。
TableA的SELECT命令
SELECT [ID], [Date], [SUM]
FROM TableA
结果
ID | Date | SUM
1 | 1/1/2010 | 2
1 | 1/2/2010 | 4
3 | 1/3/2010 | 6
TableB的SELECT命令
SELECT [ID], [Date], [SUM]
FROM TableB
结果
ID | Date | SUM
1 | 1/1/2010 | 5
1 | 2/1/2010 | 3
1 | 31/1/2010 | 2
2 | 1/2/2010 | 20
我想要输出如下
ID | Date | SUMA | SUMB
1 | 1/1/2010 | 2 | 10
1 | 1/2/2010 | 4 | 0
2 | 1/2/2010 | 0 | 20
3 | 1/3/2010 | 6 | 0
如何在SQL Server 2005上执行此操作?
日期信息可能会有所不同,如表中的修改。
答案 0 :(得分:2)
试试这个......
SELECT
ISNULL(TableA.ID, TableB.ID) ID,
ISNULL(TableA.Date, TableB.Date),
ISNULL(TableA.Sum,0) SUMA,
ISNULL(TableB.Sum, 0) SUMB
FROM
TableA FULL OUTER JOIN TableB
ON TableA.ID = TableB.ID AND TableA.Date = TableB.Date
ORDER BY
ID
您需要full outer join,因为无论是否匹配,您都希望包含两个表的结果。
答案 1 :(得分:0)
我通常将两个查询合并在一起,然后将它们分组:
SELECT ID, [Date], SUM(SUMA) As SUMA, SUM(SUMB) AS SUMB
FROM (
SELECT ID, [Date], SUMA, 0 AS SUMB
FROM TableA
UNION ALL
SELECT ID, [Date], 0 As SUMA, SUMB
FROM TableB
)
GROUP BY ID, [Date]
答案 2 :(得分:0)
SELECT
ISNULL(a.ID, b.ID) AS ID,
ISNULL(a.Date, b.Date) AS Date,
ISNULL(a.SUM, 0) AS SUMA,
ISNULL(b.SUM, 0) AS SUMB,
FROM
TableA AS a
FULL JOIN
TableB AS b
ON a.ID = b.ID
AND a.Date = b.Date;
答案 3 :(得分:0)
如何组合这两个表并不明显。我想这就是你所追求的,但你能确认一下吗?