我正在尝试使用下面的查询(完美地工作),作为UPDATE语句的子查询,并且需要在该UPDATE语句中引用值CORRECT_DATE。如果我可以在此查询中成功地选择该值,那么将其传递给UPDATE将很容易,但我似乎无法选择下面的相关子查询值并在不等式中使用它。
SELECT A.NAME, MAX(A.[START])
FROM dbo.TANK A
WHERE A.[CURRENT] = 0 AND A.[END] < (SELECT B.[START] AS CORRECT_DATE
FROM dbo.TANK B
WHERE B.[CURRENT] = 1
AND A.NAME = B.NAME
AND A.TYPE = B.TYPE
AND A.COVER = B.COVER)
我尝试过以下操作,但它不识别WHERE子句中的别名:
SELECT A.NAME, MAX(A.[START]), (SELECT B.[START] AS CORRECT_DATE
FROM dbo.TANK B
WHERE B.[CURRENT] = 1
AND A.NAME = B.NAME
AND A.TYPE = B.TYPE
AND A.COVER = B.COVER) as subvalue
FROM dbo.TANK A
WHERE A.[CURRENT] = 0 AND A.[END] < subvalue
答案 0 :(得分:2)
为什么不使用加入?相关的子查询是应尽可能避免的性能杀手。
SELECT A.NAME
, MAX(A.[START])
, B.[START]
FROM dbo.TANK A
JOIN dbo.TANK B
ON A.NAME = B.NAME
AND A.TYPE = B.TYPE
AND A.COVER = B.COVER AND B.[CURRENT] = 1
WHERE A.[CURRENT] = 0 AND A.[END] < B.[START]
GROUP BY A.NAME, B.[START];