SQL选择Top 3到单独的列中

时间:2015-09-03 15:05:34

标签: sql-server-2008 tsql

我有一个非常简单的查询,它从表中选择前3个代码,我想将它们作为单独的列值存储在临时表中,或者获取到单独的声明字段中。

前3个查询:

 select  top 3 code
 from table1 t1 (NOLOCK)
 join table2 t2 (NOLOCK) on t1.codeid = t2.codeid
 where t2.recordid = '123456789'
 and t1.codetype = '987654'

结果:

  code  
  1111 
  2222
  3333 

首选输出:

  code1     code 2     code3 
  1111      2222       3333 

我也可以选择其他类似的东西:

 Declare @code1 as varchar(4)
 Declare @code2 as varchar(4)
 Declare @code3 as varchar(4)
 DECLARE RULE_CURSOR CURSOR STATIC FOR
 {select statement here}

 OPEN RULE_CURSOR
    FETCH NEXT FROM RULE_CURSOR into @code1, @code2, @code3

如果有人可以帮助我,那么Declare和Fetch into实际上是我的首选方法。

谢谢!

1 个答案:

答案 0 :(得分:0)

我想我从之前询问过的一个单独的帖子中找到了它:

 DECLARE RULE_CURSOR CURSOR STATIC FOR
      WITH    cte
      AS ( SELECT   top 3 code,  ROW_NUMBER() over( order by code) rn
           from  Table1 T1 (NOLOCK)
           join table2 t2 (NOLOCK) on t1.codeid = t2.codeid
           where t2.recordid = '123456789'
           and t1.codetype = '987654')
 SELECT [1] AS Code1 ,
        [2] AS Code2 ,
        [3] AS Code3
 FROM cte PIVOT( MAX(code) FOR rn IN ( [1], [2], [3] ) ) a
        Open RULE_CURSOR
     FETCH NEXT FROM RULE_CURSOR into @code1, @code2, @code3