在没有循环的情况下选择TOP 2结果变量

时间:2013-09-12 07:23:30

标签: sql sql-server sql-server-2008 variables

我想将前2个结果存储在2个变量中。

create table t(id int);
insert into t (id) values (1),(2),(3),(4);

declare @id1 int
declare @id2 int

select top 2 @id1 = first id, 
             @id2 = next id
from t

SQLFiddle

我可以在不使用循环的情况下在一个查询中执行此操作吗?

6 个答案:

答案 0 :(得分:5)

declare @id1 int,@id2 int

;with cte as (
  select top (2) id
  from t
  order by id
)
select @id1 = min(id), @id2 = max(id)
from cte

select @id1,@id2

<强> Fiddle demo

答案 1 :(得分:3)

with cte as (
    select top 2 id, row_number() over(order by id) as rn
    from t
    order by id
)
select
    @id1 = (select id from cte where rn = 1),
    @id2 = (select id from cte where rn = 2)

with cte as (
    select top 2 id, row_number() over(order by id) as rn
    from t
    order by id
)
select
    @id1 = max(case when rn = 1 then id end),
    @id2 = max(case when rn = 2 then id end)
from cte

<强> sql fiddle demo

答案 2 :(得分:2)

您可以将LEAD()用于SQL Server 2012。

SELECT TOP 1 @id1 = ID, @id2 = LEAD(ID) OVER (ORDER BY ID) FROM t

答案 3 :(得分:1)

有两个SELECT,很容易......

DECLARE @id1 INT
DECLARE @id2 INT

SELECT TOP 1 @id1 = x.id 
    FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM t) x 
WHERE x.RN = 1

SELECT TOP 1 @id2 = x.id 
    FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM t) x 
WHERE x.RN = 2

SELECT @id1, @id2

使用SQL 2012,你显然可以

SELECT @id1 = id 
    FROM t ORDER BY id OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY

SELECT @id2 = id 
    FROM t ORDER BY id OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY

或者在2008年你可以

; WITH Base AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM t   
)

SELECT @id1 = b1.id, @id2 = b2.id
    FROM Base b1, Base b2
    WHERE b1.RN = 1 AND B2.RN = 2

答案 4 :(得分:0)

declare @id1 int
declare @id2 int

declare @table table(id int,rownum int)

insert into @table
select top 2 id,row_number() over( order by id) as rn from t

select @id1=case rownum when 1 then id else @id1 end,
@id2=case rownum when 2 then id end from @table

select @id1,@id2

SQL FIDDLE

答案 5 :(得分:0)

2选择更简单:

declare @id1 int
declare @id2 int
select top 1 @id1 = id from t
select top 2 @id2 = id from t
select @id1, @id2

SQL Fiddle