在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
这可用于工作,但需要散列连接。希望有人在这方面打洞或提供更有效的解决方案。感谢。
答案 0 :(得分:0)
如果每个参考号不能有重复的订单号或跟踪号,您可以使用常规LEFT JOIN
或JOIN
稍微简化查询;
SELECT mt.id, mt.refnum, mt.label, mt.value, mt.status,
ordno.value ordernum, trackno.value trackingnum
FROM myTable mt
LEFT JOIN myTable ordno
ON ordno.label='ordernum' and mt.refnum=ordno.refnum
LEFT JOIN myTable trackno
ON trackno.label='trackingnum' and mt.refnum=trackno.refnum
WHERE mt.status = 0;
如果可能存在重复项,您仍然可以执行一次GROUP BY
来获得结果;
SELECT mt.id, mt.refnum, mt.label, mt.value, mt.status,
MAX(ordno.value) ordernum, MAX(trackno.value) trackingnum
FROM myTable mt
LEFT JOIN myTable ordno
ON ordno.label='ordernum' and mt.refnum=ordno.refnum
LEFT JOIN myTable trackno
ON trackno.label='trackingnum' and mt.refnum=trackno.refnum
WHERE mt.status = 0
GROUP BY mt.id,mt.refnum,mt.label,mt.value,mt.status;