ORDER BY和带别名的列的CASE语句

时间:2010-06-28 17:20:10

标签: sql sql-server tsql sql-server-2008

我需要一个存储过程,它允许我根据两个输入参数返回排序结果:@sortColumnName和@sortDirection。我编写了以下存储过程,但是当我运行它时,我收到此错误:“无效的列名称'LastPayCheckDate'。”

SELECT Name, SUM(Pay), MAX(PayCheckDate) as LastPayCheckDate
FROM Employee
GROUP BY Name
ORDER BY 
    CASE WHEN @sortColumnName = 'LastPayCheckDate' AND @sortDirection = 'ASC'
        THEN [LastPayCheckDate] END ASC,
    CASE WHEN @sortColumnName = 'LastPayCheckDate' AND @sortDirection = 'DESC'
        THEN [LastPayCheckDate] END DESC

发生了什么事?我想t-sql在选择之前运行case语句......我是对的吗?我该如何解决这个问题?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

试试这个

ORDER BY 
    CASE WHEN @sortColumnName = 'LastPayCheckDate' AND @sortDirection = 'ASC'
        THEN MAX(PayCheckDate) END ASC,
    CASE WHEN @sortColumnName = 'LastPayCheckDate' AND @sortDirection = 'DESC'
        THEN MAX(PayCheckDate) END DESC

实施例

create table Test (id int, somevalue int)

insert Test values(1,1)
insert Test values(2,1)
insert Test values(3,2)
insert Test values(3,2)
insert Test values(4,2)

一次性运行

declare @sortDirection char(4)
select  @sortDirection = 'DESC'

select somevalue, COUNT(*)
 from Test
 group by somevalue 
 order by case when @sortDirection = 'ASC'
 then COUNT(*) end asc,
 case when @sortDirection = 'DESC'
 then COUNT(*) end desc

 select  @sortDirection = 'ASC'
 select somevalue, COUNT(*)
 from Test
 group by somevalue 
 order by case when @sortDirection = 'ASC'
 then COUNT(*) end asc,
 case when @sortDirection = 'DESC'
 then COUNT(*) end desc

答案 1 :(得分:0)

如果希望能够引用列别名,则需要再次使用该函数或使用子查询。

另外,我认为您需要确保case语句中的所有列都转换为相同的数据类型。