how to generate a query in SQL SERVER 2005 which g

2019-03-05 03:50发布

问题:

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

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

Give me an Idea.

回答1:

Something like this using CTE and 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

results:

| 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 |


回答2:

I can't see how to do it with a pivot given the lack of extra columns in the query making aggregation difficult. If you do have other columns then pivot would be less code consuming; but I'm not a pivot expert. You can do it easily enough with a few joins … used my tally table to generate the list of integers

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

Returns

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