2013-01-22 43 views
0

我試圖設置一個基於內部連接條件的標誌,我需要的是在查詢中使用order by子句導致我的條件依賴於具有特定字符串的最後一條記錄,但不能是最後一個表,我試過它說什麼不允許,我試過的東西似乎不適合我。在更新語句中排序不允許

第一次嘗試:


UPDATE TESTINSTANCE SET NETWORKOUTAGE='1' 
WHERE TESTINSTANCEID IN (SELECT DISTINCT A.TESTINSTANCEID FROM AUDITLOG A 
INNER JOIN TESTINSTANCE TI ON TI.TESTINSTANCEID=A.TESTINSTANCEID AND TI.TIMETAKEN IS NULL 
AND TI.NETWORKOUTAGE!='1' 
AND TI.ISSENTTOEDUNXT IS NULL 
WHERE REPLACE(A.MESSAGE, ' ', '')=REPLACE('PING RESPONSE CAME FROM SERVER',' ','') 
AND DATEDIFF (MINUTE, A.REPORTEDTIME, GETDATE())>=5 ORDER BY A.AUDITID DESC); 

二試過


UPDATE TI SET NETWORKOUTAGE='1' 
FROM TESTINSTANCE TI INNER JOIN (SELECT DISTINCT A.TESTINSTANCEID FROM AUDITLOG A 
INNER JOIN TESTINSTANCE TI ON TI.TESTINSTANCEID=A.TESTINSTANCEID AND TI.TIMETAKEN IS NULL 
AND TI.NETWORKOUTAGE!='1' 
AND TI.ISSENTTOEDUNXT IS NULL 
WHERE REPLACE(A.MESSAGE, ' ', '')=REPLACE('PING RESPONSE CAME FROM SERVER',' ','') 
AND DATEDIFF (MINUTE, A.REPORTEDTIME, GETDATE())>=5 ORDER BY A.AUDITID DESC) RES ON RES.TESTINSTANCEID=TI.TESTINSTANCEID; 

但兩者給我同樣的錯誤,

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified. 

我在這裏錯過了什麼?

回答

0

看到你想要做什麼有點棘手,顯然我們沒有你的表格。但我想你想要的東西是這樣的:

.... (SELECT A.TESTINSTANCEID,A.REPORTEDTIME, 
    ROW_NUMBER() OVER (PARTITION BY A.TESTINSTANCEID ORDER BY A.AUDITID DESC) as RN 
... 

) RES ON RES.TESTINSTANCEID=TI.TESTINSTANCEID AND 
    RES.RN = 1 AND 
    DATEDIFF (MINUTE, RES.REPORTEDTIME, GETDATE())>=5 

並從子查詢中刪除日期比較。基本上,使子查詢編號適當的行,這樣,在連接條件下,您可以選擇只是最新的行,並使用該值REPORTEDTIME值。

+0

感謝您的建議好友。 – joshua