在sql server中选择语句以交替选择每隔一行

时间:2015-03-23 03:33:36

标签: sql sql-server tsql

我们有一个名为“Result”的表只有一列说“Result”。 它包含12行。前6行包含“pass”,后6行包含“fail”

Result
---------------------
pass
pass
pass
pass
pass
pass
fail
fail
fail
fail
fail
fail

现在,SQL Query中的语句将返回如下所示的返回值

Expected Result:-
pass
fail
pass
fail
pass
fail
pass
fail
pass
fail
pass
fail

记录数量可能是数千,但查询应该适用于所有

2 个答案:

答案 0 :(得分:2)

实际上你需要: 序列:one row from end, one row from beginning,...and so on until all rows get selected所以将所有传递设为ODD,所有传递都以EVEN传递,现在您可以根据您所做的数字选择和排序:

with CTE as
(
  select result , row_number() over(partition by result order by result) as rn
  from result
)
select result,
  case
  when result='fail' then rn*2 else rn*2 -1  end rn
from CTE 
order by rn

SQLFIDDLE DEMO

答案 1 :(得分:0)

选择结果(选择row_number()over(按结果排序)row_num,结果得到result ='fail' 联盟 select row_number()over(order by result)row_num,result result from result ='pass')a 按row_num排序

适用于Mssql