在sql server中将一半记录分为两列,然后合并它们

在sql server中将一半记录分为两列,然后合并它们,sql,sql-server,Sql,Sql Server,以下是我的演示查询: select 1 as 'testrank', 'title1' as 'testtitle' union all select 2 as 'testrank', 'title2' as 'testtitle' union all select 3 as 'testrank', 'title3' as 'testtitle' union all select 4 as 'testrank', 'title4' as 'testtitle' union all select

以下是我的演示查询:

select 1 as 'testrank', 'title1' as 'testtitle'
union all
select 2 as 'testrank', 'title2' as 'testtitle'
union all
select 3 as 'testrank', 'title3' as 'testtitle'
union all
select 4 as 'testrank', 'title4' as 'testtitle'
union all
select 5 as 'testrank', 'title5' as 'testtitle'
union all
select 6 as 'testrank', 'title6' as 'testtitle'
我想把一半的记录分为两部分,在本例中是3。出于演示目的,我在下面编写了查询,这是所需的输出

select 1 as 'testrank', 'title1' as 'testtitle', 4 as 'testrank2', 'title4' as 'testtitle2'
union all
select 2 as 'testrank', 'title2' as 'testtitle', 5 as 'testrank2', 'title5' as 'testtitle2'
union all
select 3 as 'testrank', 'title3' as 'testtitle', 6 as 'testrank2', 'title6' as 'testtitle2'
我尝试使用Pivot,使用rownumber,但不知何故,我无法实现所需的输出。 欢迎提出任何建议

ntile(2)
将您的行分成两行,
行编号()
将枚举每个组。主查询连接生成的
行编号()上的组

SELECT 
CASE Ranking WHEN 1 THEN  testrank  ELSE NULL END AS A ,
CASE Ranking WHEN 1 THEN  testtitle  ELSE NULL END AS B ,
CASE Ranking WHEN 2 THEN  testrank  ELSE NULL END AS A1 ,
CASE Ranking WHEN 2 THEN  testtitle  ELSE NULL END AS B1
FROM 
(
SELECT *,NTILE(2) OVER (ORDER BY testrank) AS Ranking
FROM
(
select 1 as 'testrank', 'title1' as 'testtitle'
union all
select 2 as 'testrank', 'title2' as 'testtitle'
union all
select 3 as 'testrank', 'title3' as 'testtitle'
union all
select 4 as 'testrank', 'title4' as 'testtitle'
union all
select 5 as 'testrank', 'title5' as 'testtitle'
union all
select 6 as 'testrank', 'title6' as 'testtitle'
)AS T
)AS T1

最好在比数据库更高的级别上进行这种格式化。不要这样做!这是糟糕的模式设计。担心演示层中的布局,而不是数据层中的布局。您可能需要编辑问题,突出显示代码并点击
{}
按钮。添加一些解释也不会有什么坏处。谢谢Vikas,但仍然不是期望的结果。它为那些没有记录的列提供了不需要的null记录,因此我无法获得所需的输出。你能建议一些不同的方法吗。
with C1 as
(
  select testrank,
        testtitle,
        ntile(2) over(order by testrank) as n
  from YourTable
), C2 as
(
  select testrank,
         testtitle,
         n,
         row_number() over(partition by n order by testrank) as rn
  from C1
)

select T1.testrank,
       T1.testtitle,
       T2.testrank as testrank2,
       T2.testtitle as testtitle2
from C2 as T1
  left outer join C2 as T2
    on T1.rn = T2.rn and
       T2.n = 2
where T1.n = 1