查询以矩阵格式显示数据库中的数据

时间:2013-11-05 06:53:46

标签: sql sql-server matrix pivot

我在数据库中的数据从1到32

开始
1
2
3
4
5
-
-
32

我需要以4列和8行显示数据,如

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以上述格式显示数据表中的数据。 我对这种格式没有任何想法以显示矩阵格式(4X6)。

1 个答案:

答案 0 :(得分:1)

检查出来

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
相关问题