将一半记录分配到sql server中的两列中,然后合并它们

时间:2014-01-10 06:27:36

标签: 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 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'

我使用rownumber尝试使用Pivot,但不知怎的,我无法实现所需的输出。 任何建议都会受到欢迎。

2 个答案:

答案 0 :(得分:0)

ntile(2)会将您的行分为两部分,row_number()将枚举每个组。主查询在生成的row_number()上加入组。

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

答案 1 :(得分:-1)

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