在 order by 子句之前使用 case 语句
Using case statement before order by clause
我想在 Order By 之前有一个条件语句。
在我下面的查询中,Marks 有可能为空,在这种情况下,我想按 Rank Asc
排序
SELECT TOP 1 P.[Score]
FROM dbo.[Profile] P
WHERE P.[ProfileId] = @ProfileId
ORDER BY P.[Marks] DESC AS [ProfileScore]
我尝试将其更改为以下方式,但出现编译错误
SELECT TOP 1 P.[Score]
FROM dbo.[Profile] P
WHERE P.[ProfileId] = @ProfileId
ORDER BY
(CASE WHEN P.[Marks] IS NOT NULL THEN P.[Marks] END) DESC,
(CASE WHEN P.[Marks] IS NULL THEN P.[Rank] END) ASC AS [ProfileScore]
但是报错:
Incorrect syntax near the keyword 'DESC'
您的 ORDER BY
中 AS [ProfileScore]
太多了。您不能在 ORDER BY
.
中创建别名
如果Marks
和Rank
都是数字,我建议:
SELECT TOP 1 P.[Score]
FROM dbo.[Profile] P
WHERE P.[ProfileId] = @ProfileId
ORDER BY CASE WHEN P.[Marks] IS NULL THEN P.[Rank] ELSE -P.[Marks] END;
我想在 Order By 之前有一个条件语句。
在我下面的查询中,Marks 有可能为空,在这种情况下,我想按 Rank Asc
排序SELECT TOP 1 P.[Score]
FROM dbo.[Profile] P
WHERE P.[ProfileId] = @ProfileId
ORDER BY P.[Marks] DESC AS [ProfileScore]
我尝试将其更改为以下方式,但出现编译错误
SELECT TOP 1 P.[Score]
FROM dbo.[Profile] P
WHERE P.[ProfileId] = @ProfileId
ORDER BY
(CASE WHEN P.[Marks] IS NOT NULL THEN P.[Marks] END) DESC,
(CASE WHEN P.[Marks] IS NULL THEN P.[Rank] END) ASC AS [ProfileScore]
但是报错:
Incorrect syntax near the keyword 'DESC'
您的 ORDER BY
中 AS [ProfileScore]
太多了。您不能在 ORDER BY
.
如果Marks
和Rank
都是数字,我建议:
SELECT TOP 1 P.[Score]
FROM dbo.[Profile] P
WHERE P.[ProfileId] = @ProfileId
ORDER BY CASE WHEN P.[Marks] IS NULL THEN P.[Rank] ELSE -P.[Marks] END;