2013-11-02 57 views
0

H我有32行組成的列。像如何在SQL SERVER 2005中生成一個類似Matrix的輸出查詢?

ColumnA 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 

在檢索我想要的(4×8)指4列8 Rows.The結果應該是這樣的

A B C D 
1 9 17 25 
2 10 18 26 
3 11 19 27 
4 12 20 28 
5 13 21 29 
6 14 22 30 
7 15 23 31 
8 16 24 32 

給我一個想法。

+0

你見過'PIVOT'條款嗎? –

+0

沒有。我不支持 – Anjali

回答

1

像這樣使用CTErow_number()

Fiddle demo

declare @numRows int = 8 

;with cte as (
    select columnA X, row_number() over (order by columnA) rn 
    from Table1 
) 
select c1.x A, c2.x B, c3.x C, c4.x D 
from cte c1 
    left join cte c2 on c1.rn = [email protected] 
    left join cte c3 on c1.rn = c3.rn-(@numRows * 2) 
    left join cte c4 on c1.rn = c4.rn-(@numRows * 3) 
where c1.rn <= @numRows 

結果:

| A | B | C | D | 
|---|----|----|----| 
| 1 | 9 | 17 | 25 | 
| 2 | 10 | 18 | 26 | 
| 3 | 11 | 19 | 27 | 
| 4 | 12 | 20 | 28 | 
| 5 | 13 | 21 | 29 | 
| 6 | 14 | 22 | 30 | 
| 7 | 15 | 23 | 31 | 
| 8 | 16 | 24 | 32 | 
+0

謝謝它對我有用.., – Anjali

+0

r你記得我吧, – Anjali

+0

是的你是對的 – Anjali

1

由於查詢中缺少額外的列使聚合變得困難,我無法看到如何使用主元。如果你確實有其他列,那麼樞軸將會減少代碼消耗;但我不是樞軸專家。你可以這樣做很輕鬆地與幾個加入......用我的理貨表來生成一個整數列表

SELECT 

aa.StaticInteger as A, 
bb.StaticInteger as B, 
cc.StaticInteger as C, 
dd.StaticInteger as D 

FROM 
    tblTally aa 

LEFT OUTER JOIN 
(
SELECT 
StaticInteger 
FROM 
    tblTally 
WHERE 
    StaticInteger BETWEEN 9 AND 16 
) bb 
ON 
    aa.StaticInteger = bb.StaticInteger - 8 

LEFT OUTER JOIN 
(
SELECT 
    StaticInteger 
FROM 
    tblTally 
WHERE 
    StaticInteger BETWEEN 17 AND 24 
) cc 
ON 
    bb.StaticInteger = cc.StaticInteger - 8 

LEFT OUTER JOIN 
(
SELECT 
    StaticInteger 
FROM 
    tblTally 
WHERE 
    StaticInteger BETWEEN 25 AND 32 
) dd 
ON 
    cc.StaticInteger = dd.StaticInteger - 8 

WHERE 
    aa.StaticInteger BETWEEN 1 AND 8 

返回

A B C D 
1 9 17 25 
2 10 18 26 
3 11 19 27 
4 12 20 28 
5 13 21 29 
6 14 22 30 
7 15 23 31 
8 16 24 32