2014-01-10 23 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,但仍然不是理想的結果。它給我不需要的記錄爲空的那些沒有記錄的列,所以我無法得到所需的輸出。你能提出一些不同的方法嗎? –

相關問題