问题
I accidentally ran a query twice and all the points in my database have messed up (3000 records).
Top 4 for each result has fixed results but points between last and 5th are calculated (Last is 100pts).
Click here for more info
I essentially need this statement converting to SQL:
Points = 100 + ((100 / (NumberOfResults - 4)) * (NumberOfResults - PositionOfResult))
How can I get a select statement to refer to the Select and the Update table separately. This doesn't work:
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)
回答1:
I would pre-calculate the top values and store them in a temporary table before performing the UPDATE:
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);
However, I am not sure how NumberOfResults
and NumberOfPlaces
are defined. You are selecting a top position but are never calculating any numbers. Maybe you can add this to the SELECT:
...,
(SELECT COUNT(*)
FROM Results R2
WHERE R2.Date = R1.Date AND R2.ContestID = R1.ContestID) AS NumberOfResults
INTO ...
回答2:
Just needed the update to show from the correct table using "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)
来源:https://stackoverflow.com/questions/27323852/messed-up-sql-data-select-within-update-statement