0

您好,我有一列由 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

而检索我想要(4 X 8)意味着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

给我一个想法。

4

2 回答 2

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
于 2013-11-02T14:10:46.783 回答
1

像这样使用CTEand row_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

结果:

| 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 |
于 2013-11-02T15:59:02.947 回答