Sql server 2005 如何在SQLServer2005中生成一个像矩阵一样输出的查询?

Sql server 2005 如何在SQLServer2005中生成一个像矩阵一样输出的查询?,sql-server-2005,matrix,Sql Server 2005,Matrix,H我有一个由32行组成的列。像 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 当检索i-want(4x8)时,表示4列8行 A B C D 1 9 17 25 2 10 18 26 3 11 19 27 4 12 20 28

H我有一个由32行组成的列。像

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
当检索i-want(4x8)时,表示4列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

给我一个主意。

我看不出如何使用pivot,因为查询中缺少额外的列,这使得聚合很困难。如果您有其他列,那么pivot将更少地消耗代码;但我不是一个支点专家。你可以很容易地做一些连接…使用我的计数表来生成整数列表

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

使用
CTE
row\u number()
类似的内容:

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

你看过
PIVOT
子句吗?
| 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 |