SQL从一列中的两列获取记录

时间:2014-12-04 11:02:57

标签: sql sql-server

我试图从两列获取记录,使得输出包含来自1st col的1条记录,然后是来自2nd col的第1条记录。

senario就像这样

ColA     ColB
1         a
2         b
3         c

Output
1
a
2
b
3
c

2 个答案:

答案 0 :(得分:0)

SELECT x.Output FROM
(
   SELECT Output = CAST(ColA AS VARCHAR(10)), 
          RN = ROW_NUMBER()OVER(ORDER BY ColA,ColB)
   FROM TableName 

   UNION ALL 

   SELECT Output = ColB, 
          RN = ROW_NUMBER()OVER(ORDER BY ColA,ColB)
   FROM TableName 
) X
ORDER BY x.RN

演示:http://sqlfiddle.com/#!6/7f3cf/4/0

答案 1 :(得分:0)

这是一种没有窗口函数的方法,假设ColA指定了行的排序:

select output
from ((select cola as output, cola as ordering, 'a' as which
       from table t
      ) union all
      (select colb, cola, 'b'
       from table t
      )
     ) t
order by ordering, which;

请注意,这将保证值在结果集中交错。