2014-12-05 54 views
1

我意外地運行了一次查詢兩次,並且我的數據庫中的所有點都弄亂了(3000條記錄)。每個結果搞砸了SQL數據 - 在更新語句中選擇

4強已經固定去年和5之間的結果,但點計算(去年是100pts)。

Click here更多信息

我基本上是需要這個語句轉換爲SQL:

分= 100 +((100 /(NumberOfResults - 4))*(NumberOfResults - PositionOfResult))

如何獲得select語句以分別引用Select和Update表。這不起作用:

UPDATE Results R1 
SET  R1.Points = 100 + ((100/((SELECT TOP 1 R2.Position FROM Results R2 WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID ORDER BY R2.Position DESC)-4) * ((SELECT TOP 1 R2.Position FROM Results R2 WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID ORDER BY R2.Position DESC)-R1.Position))) 
WHERE  R1.ContestID > 11 
AND  R1.Position > 4 
AND  R1.Position < (SELECT TOP 1 R2.Position FROM Results R2 WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID ORDER BY R2.Position DESC) 
+0

遺憾的髒話,這是複製並粘貼@amimunson – 2014-12-05 20:20:58

回答

1

只是需要更新,從正確的表顯示了使用「FROM」

UPDATE R1 
SET  R1.Points = 100 + ((100/((SELECT TOP 1 R2.Position FROM Results R2 WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID ORDER BY R2.Position DESC)-4) * ((SELECT TOP 1 R2.Position FROM Results R2 WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID ORDER BY R2.Position DESC)-R1.Position))) 
From  Results R1 
WHERE  R1.ContestID > 11 
AND  R1.Position > 4 
AND  R1.Position < (SELECT TOP 1 R2.Position FROM Results R2 WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID ORDER BY R2.Position DESC) 
1

我會預先計算的頂值和執行更新之前臨時表它們存儲:

SELECT 
    R1.Date, 
    R1.ContestID, 
    (SELECT TOP 1 R2.Position 
    FROM Results R2 
    WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID 
    ORDER BY R2.Position DESC) AS TopPosition 
INTO #temp 
FROM 
    (SELECT DISTINCT Date, ContestID FROM Results) R1; 

UPDATE Results R 
SET R.Points = 100 + ((100/((SELECT TopPosition FROM #temp T 
           WHERE T.Date = R.Date AND 
             T.ContestID = R.ContestID)-4) * 
          ((SELECT TopPosition FROM #temp T 
           WHERE T.Date = R.Date AND 
            T.ContestID = R.ContestID)-R.Position))) 
WHERE R.ContestID > 11 
AND R.Position > 4 
AND R.Position < (SELECT TopPosition FROM #temp T 
        WHERE T.Date = R.Date AND T.ContestID = R.ContestID); 

但是,我不知道如何NumberOfResultsNumberOfPlaces被定義。您正在選擇頂部位置,但從不計算任何數字。也許你可以將它添加到SELECT:

..., 
(SELECT COUNT(*) 
FROM Results R2 
WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID) AS NumberOfResults 
INTO ... 
+0

NumberOfResults和地點的數量是一樣的,比賽當天有多少結果。可能有5支球隊參賽,或者12支,或者其他任何東西!我應該更清楚 – 2014-12-05 23:19:48

+0

如果職位編號爲1,2,3 ... NumberOfResults,那麼兩個變體'SELECT TOP 1 Position ... ORDER BY Position DESC'和'SELECT COUNT(*)'應該返回相同的結果。 – 2014-12-05 23:28:34

+0

我在「R」上收到錯誤。和「結果R」。我們可以在更新語句中使用這個語法嗎? – 2014-12-06 01:01:07