如何在SQL SERVER 2005中生成查询,该查询给出类似Matrix的输出? [英] how to generate a query in SQL SERVER 2005 which gives output like Matrix?
本文介绍了如何在SQL SERVER 2005中生成查询,该查询给出类似Matrix的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
H我具有由32行组成的列.像
H i have column which consists of 32 rows. like
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 X 8)表示4列8行.结果应该是这样
while retrieving i want (4 X 8) means 4 columns 8 Rows.The Result should be like this
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
给我一个主意.
推荐答案
使用CTE
和row_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 = c2.rn-@numRows
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 |
这篇关于如何在SQL SERVER 2005中生成查询,该查询给出类似Matrix的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文