如何加入这两个表

时间:2013-01-14 10:56:37

标签: sql sql-server-2008

我有两张桌子:

表“一”:

ServiceID, ApplicationCode, Success
1, 1, 2
1, 3, 2
2, NULL, 3

表“两个”:

ServiceID, ApplicationCode, Failure
1, 1, 1
1, 2, 3
2, NULL, 4
3, NULL, 1

我希望收到结果表

列:

ServiceID, ApplicationCode, Success, Failure
1, 1, 2, 1
1, 3, 2, NULL
2, NULL, 3, 4
1, 2, NULL, 3
3, NULL, NULL, 1

我正在使用SQL Server 2008。

我应该使用什么查询?

已编辑:我想通过ServiceID和ApplicationCode加入这两个表。

编辑2: 代码我尝试过:

INSERT INTO #MidResult(ServiceID,ApplicationCode,SuccessCount,FailureCount)
SELECT case rtrim(ltrim(s.ServiceID)) WHEN NULL THEN f.ServiceID ELSE s.ServiceID END,s.ApplicationCode,s.SuccessCount,f.FailureCount
FROM #SuccessResult s
FULL JOIN #FailureResult f on f.ApplicationCode = s.ApplicationCode and s.ServiceID = f.ServiceID

2 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

select 
  coalesce(t1.serviceid, t2.serviceid) serviceid,
  coalesce(t1.ApplicationCode, t2.ApplicationCode) ApplicationCode,
  t1.Success,
  t2.failure
from table1 t1
full outer join table2 t2
  on t1.ServiceID = t2.ServiceID
  and isnull(t1.ApplicationCode, '') = isnull(t2.ApplicationCode, '')
order by serviceid, ApplicationCode

请参阅SQL Fiddle with Demo

结果是:

| SERVICEID | APPLICATIONCODE | SUCCESS | FAILURE |
---------------------------------------------------
|         1 |               1 |       2 |       1 |
|         1 |               2 |  (null) |       3 |
|         1 |               3 |       2 |  (null) |
|         2 |          (null) |       3 |       4 |
|         3 |          (null) |  (null) |       1 |

答案 1 :(得分:-1)

Select one.ServiceID, one.ApplicationCode, one.Success, two.Failure
From TableOne one , TableTwo two
where one.ServiceID = two.ServiceID
and one.ApplicationCode = two.ApplicationCode

注意ServiceID和ApplicationCode都应匹配。