【发布时间】:2019-05-22 16:23:21
【问题描述】:
在以下查询中,我使用@IsDescOrder 来设置排序。
我尝试指定order by(即ASC 或DESC)但出现错误。我可以删除 DESC | ASC 但两个选项将返回相同的集合,因为它将返回默认排序:
declare @IsDescOrder bit = 0
;with cte as
(
select
*
from (
select *, r = row_number() over (partition by NameId
order by
case @IsDescOrder
when 1 then size_mbps DESC,
when 0 then size_mbps ASC
end
)
from #temp_table
) a
where r <= 20
)
select
* from
cte
我收到错误Incorrect syntax near the keyword 'DESC'.。
有解决办法吗?
【问题讨论】:
-
旁白:请注意,
case表达式具有单一数据类型。如果您将MyTableId(可能是Int)和DateKey(可能是Date)混合在一起,那么data type precedence 的规则规定结果将始终是Date。一些数据类型,例如Int,可以使用否定进行升序或降序排序:case when @Ascending = 1 then FooId else -FooId end。
标签: sql-server tsql sql-server-2008