我尝试使用case语句通过外部select语句中的列来排序,以确定要排序的字段。出于某种原因,我无法使用外部选择中创建的列。如果我尝试按该列排序而不使用case语句,那么它可以工作。我做错了什么?
伪代码来说明问题:
DECLARE @orderBy varchar(8)
SET @orderBy = 'rating'
SELECT
CASE
WHEN rating is not null THEN 1
ELSE 0
END as hasRating,
*
FROM
(SELECT col1, ...) AS table1
LEFT OUTER JOIN
(SELECT col1, rating, ...) AS table2
ON table1.col1 = table2.col2
--causes error "Invalid column name 'hasRating'"
ORDER BY
CASE WHEN @orderBy = 'rating' THEN hasRating END DESC,
CASE WHEN @orderby = 'something else' THEN ...
--works
ORDER BY hasRating desc
答案 0 :(得分:5)
这会引发错误:
ORDER BY
CASE WHEN @orderBy = 'rating' THEN CASE WHEN rating is not null THEN 1 ELSE 0 END END DESC,
CASE WHEN @orderby = 'something else' THEN ...
似乎在别名可用之前评估CASE
中的ORDER
。