0

在 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

这似乎可以工作,但需要哈希连接。希望有人在这方面打出漏洞或提供更有效的解决方案。谢谢。

4

1 回答 1

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;

一个用于测试的 SQLfiddle

如果可能有重复,你仍然可以做一个单一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;

另一个 SQLfiddle

于 2013-07-16T17:32:17.903 回答