0

我正在尝试在 row_number 中使用变量 order by,当每个案例都有一个定义为没有 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
4

3 回答 3

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
于 2013-09-30T09:41:22.230 回答
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
于 2013-09-30T09:43:20.710 回答
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每一行生成 - 但由于所有NULLs 一起排序,这很好)

刚刚注意到并非所有列名都建议兼容类型 - 在这种情况下,这可能会更好:

 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
)

您可以CASE为所需的每种数据类型和 asc/desc 组合使用单独的语句 - 如上所述,每个语句只会为未提及NULL的任何值生成 s 。@orderby

于 2013-09-30T09:41:13.340 回答