我正在尝试在row_number中使用变量顺序,当每个案例都有一个没有asc或desc定义的单个列时,它会起作用。但是当我定义多个列或使用asc或desc时它不起作用。
这有效:
select top(@perpage) *,row_number()
over (order by
case @orderby when 'updated' then date_edited
when 'oldest' then date_added
end
)
as rid from
(select * from ads) a
where rid>=@start and rid<@start+@perpage
但我想这样做:
select top(@perpage) *,row_number()
over (order by
case @orderby when 'updated' then date_edited, user_type desc
when 'oldest' then date_added, user_type desc
when 'newest' then date_added desc, user_type desc
when 'mostexpensive' then price desc, user_type desc
when 'cheapest' then pricedesc, user_type desc
when '' then user_type desc
end
)
as rid from
(select * from ads) a
where rid>=@start and rid<@start+@perpage
答案 0 :(得分:1)
请改为尝试:
select top(@perpage) *,row_number()
over (order by
case @orderby when 'updated' then date_edited
when 'oldest' then date_added
end,
case @orderby when 'newest' then date_added
end desc,
case @orderby when 'mostexpensive' then -price
when 'cheapest' then pricedesc
end,
user_type desc
)
as rid from ads a
where rid>=@start and rid<@start+@perpage
答案 1 :(得分:1)
试试这个
select top(@perpage) *,row_number()
over (order by
case @orderby when 'updated' then date_edited end,
case @orderby when 'oldest' then date_added end,
case @orderby when 'newest' then date_added end desc,
case @orderby when 'mostexpensive' then price end desc,
case @orderby when 'cheapest' then price end,
user_type desc
)
as rid from
(select * from ads) a
where rid>=@start and rid<@start+@perpage
答案 2 :(得分:0)
CASE
是一个返回单个值的表达式。由于第二个排序列始终相同,因此您可以:
over (order by
case @orderby when 'updated' then date_edited
when 'oldest' then date_added
when 'newest' then date_added desc
when 'mostexpensive' then price desc
when 'cheapest' then pricedesc
end, user_type desc
)
(当@orderby
等于''
时,case表达式将为每一行生成NULL
- 但由于所有NULL
排序在一起,这很好)
注意到并非所有的列名称都提供了兼容的类型 - 在这种情况下,这可能会更好:
over (order by
case @orderby when 'updated' then date_edited
when 'oldest' then date_added
end,
case @orderby
when 'newest' then date_added
end desc,
case @orderby
when 'mostexpensive' then price
end desc,
case @orderby
when 'cheapest' then price
end asc,
user_type desc
)
对于每种数据类型和所需的asc / desc组合,您可以有一个单独的CASE
语句 - 如上所述,每个语句只会为任何NULL
值生成@orderby
个提及。