我有一个SQL Server 2008查询,它将计算列“点”分组。当“点”关系时,我需要查看另一个字段以确定正确的顺序。
SELECT
p.DriverID,
p.DriverName,
p.CarNum,
SUM(CASE WHEN r.RaceType = 10 THEN (200 - ((p.CarPosition - 1) * 2)) ELSE 0 END) AS Points
FROM
RaceParticipants AS p
INNER JOIN Race AS r ON p.RaceID = r.RaceID
GROUP BY
r.RaceDateID, p.DriverID, p.DriverName, p.CarNum
HAVING
(r.RaceDateID IN (255, 256))
ORDER BY
Points DESC
我需要查看的专栏是p.CarPosition WHERE r.RaceType = 60
所以它必须是某种子查询?
答案 0 :(得分:1)
类似的东西:
SELECT DriverID, DriverName,CarNum,Points
FROM (SELECT
p.DriverID,
p.DriverName,
p.CarNum,
SUM(CASE WHEN r.RaceType = 10 THEN (200 - ((p.CarPosition - 1) * 2)) ELSE 0 END) AS Points,
MAX(CASE WHEN r.RaceType = 60 THEN p.CarPosition ELSE 999999 END) AS OrderField
FROM
RaceParticipants AS p
INNER JOIN Race AS r ON p.RaceID = r.RaceID
WHERE r.RaceDateID IN (255, 256)
GROUP BY
r.RaceDateID, p.DriverID, p.DriverName, p.CarNum
)sub
ORDER BY
Points DESC, OrderField
根据您希望如何处理第二个订单字段,您可以更改ELSE
,而不会ELSE
您将返回NULL
,其中升序排序在其他值之前。< / p>