在 SQL Server 2008 中,我有一个如下所示的表:
ID | RefNum | Label | Value | Status
------------------------------------------------------
1 123 OrderNum 123456 0
2 123 TrackingNum 111111 0
3 123 ConfNum 989898 0
4 234 OrderNum 234567 1
5 234 TrackingNum 222222 1
6 234 ConfNum 878787 0
7 567 OrderNum 345678 1
8 567 TrackingNum 333333 0
9 567 ConfNum 767676 0
我想选择 Status = 0 的所有记录,并根据 RefNum 连接到“OrderNum”和“TrackingNum”标签值,无论“OrderNum”和 TrackingNum 状态是 1 还是 0。例如,查询应该产生:
ID | RefNum | Label | Value | Status |OrderNum|TrackingNum
------------------------------------------------------------------------
1 123 OrderNum 123456 0 123456 111111
2 123 TrackingNum 111111 0 123456 111111
3 123 ConfNum 989898 0 123456 111111
6 234 ConfNum 878787 0 234567 222222
8 567 TrackingNum 333333 0 345678 333333
9 567 ConfNum 767676 0 345678 333333
现在,我的查询如下所示:
SELECT Id
,mT.RefNum
,Label
,Value
,Status
,OrderNum
,TrackingNum
FROM [dbo].[myTable] AS mT
INNER JOIN (
SELECT MAX(ID) As OrderRowId, RefNum, Value AS OrderNum
FROM [dbo].[myTable]
WHERE Label= 'OrderNum'
group by RefNum, Value) AS OrderNums
ON OrderNums.RefNum= mt.RefNum
INNER JOIN (
SELECT MAX(ID) As OrderRowId, RefNum, Value AS TrackingNum
FROM [dbo].[myTable]
WHERE Label= 'TrackingNum'
group by RefNum, Value) AS TrackingNums
ON TrackingNums.RefNum= mt.RefNum
WHERE ProcessComplete = 0
这似乎可以工作,但需要哈希连接。希望有人在这方面打出漏洞或提供更有效的解决方案。谢谢。