SQL顺序但首先是所有带有userId的行

时间:2011-11-14 13:58:56

标签: sql

我有订单表,有Identity列Id,UserId和Value。

我想写一个返回按Value排序的记录的查询,但确保前n行是当前登录用户的行。

有可能吗?

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

如果您在执行查询之前知道用户ID,请尝试使用案例陈述

SELECT Id, UserId, Value,
    CASE UserId WHEN :userId THEN 1 ELSE 0 END AS UserPriority
ORDER BY UserPriority DESC, Value ASC

:userId替换为您的已知用户ID

答案 1 :(得分:0)

以下是特定于SQL Server的解决方案

declare @userid int = x
declare @n int = y  

;with a as (
  select
    row_number() over ( partition by userid order by value) as user_seq,
    case 
      when userid = @userid then 1 
      else 0 
    end as is_user,
    *
  from orders
), b as (
  select
    case 
      when is_user = 1 and user_seq <= @n then 1 
      else 0 
    end as sort_first,
    a.* 
  from a
)
select * from b
order by sort_first desc, value

答案 2 :(得分:-1)

你可以这样写。

select * from orders,users where users.id = order.userid and user.loggedin = true

union

select * from orders,users where users.id = order.userid and user.loggedin <> true