我有两张桌子:
表“一”:
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
答案 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
结果是:
| 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都应匹配。