Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

come generare una query in SQL SERVER 2005 che fornisce output come Matrix?

Qualcosa del genere usando CTE e row_number() :

Demo di violino

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 = [email protected]  
     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

risultati:

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