简体   繁体   English

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

[英]SQL get records from two columns in one column

I am trying to get records from two columns in such a way that the output contains 1 record from 1st col then 1st record from 2nd col. 我试图以这样的方式从两列中获取记录,即输出包含来自1st col的1条记录,然后包含来自2nd col的1st记录。

the senario is like this senario就是这样

ColA     ColB
1         a
2         b
3         c

Output
1
a
2
b
3
c
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

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

Here is an approach without window functions, assuming that ColA specifies the ordering for the rows: 这是一种没有窗口函数的方法,假设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;

Note that this will guarantee that the values are interleaved in the result set. 请注意,这将确保值在结果集中交错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM