1

我正在尝试使用 case 语句按外部选择语句中的列进行排序,以确定要排序的字段。出于某种原因,我无法使用在外部选择中创建的列。如果我尝试在不使用 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
4

1 回答 1

6

Does this throw an error:

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 ...

Seems like the CASE in the ORDER by is evaluated before the alias is available.

于 2013-08-16T16:23:45.893 回答