2011-10-31 129 views
0

我試圖使用下面的查詢(它完美地工作),作爲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 

回答

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]; 
+0

偉大的解決方案!不僅僅是5分鐘內的正確答案,還有一個比我的嘗試還要好!謝謝! –