2014-01-10 24 views
0

以下是我的演示查询:分发一半的记录,然后将它们合并

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,但不知何故,我无法实现所需的输出。 任何建议将受到欢迎。

+0

在比数据库更高的层次上进行这种格式化会更好。 –

+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 
+0

感谢解决方案的工作。 –

-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 
+0

您可能想编辑您的问题,突出显示代码并点击'{}'按钮。添加一些解释也不会伤害。 –

+0

感谢Vikas,但仍然不是理想的结果。它给我不需要的记录为空的那些没有记录的列,所以我无法得到所需的输出。你能提出一些不同的方法吗? –

相关问题