我在SQL Server中有这样的数据:
floor | Apartment
1 1
1 2
1 3
2 4
2 5
2 6
因为一层有3套公寓,我想将Apartment
列排序或转换成像流动的一排
4 | 5 | 6
1 | 2 | 3
答案 0 :(得分:2)
MS SQL Server 2012架构设置:
create table YourTable
(
Floor int,
Apartment int
)
go
insert into YourTable values
( 1, 1),
( 1, 2),
( 1, 3),
( 2, 4),
( 2, 5),
( 2, 6)
查询1 :
select P.Floor,
P.[1] as Room1,
P.[2] as Room2,
P.[3] as Room3
from (
select Floor,
Apartment,
row_number() over(partition by Floor order by Apartment) as rn
from YourTable
) as T
pivot(min(T.Apartment) for T.rn in ([1], [2], [3])) as P
<强> Results 强>:
| FLOOR | ROOM1 | ROOM2 | ROOM3 |
|-------|-------|-------|-------|
| 1 | 1 | 2 | 3 |
| 2 | 4 | 5 | 6 |