这是我的桌面结构!
create table t(floor int,apt int)
insert into t values(1,1),(1,2),(1,4),(2,5),(2,6),(2,7)
我想要这样!
floor room1 room2 room3
1 1 2 4
2 5 6 7
答案 0 :(得分:1)
在这种情况下使用PIVOT。
SELECT * FROM
(
SELECT floor,
apt,
NumberedApt = 'room' + CAST(ROW_NUMBER() OVER
(PARTITION BY floor ORDER BY apt) AS NVARCHAR(100))
FROM t
) AS OrderApts
PIVOT (MAX(apt) FOR Numberedapt IN (room1, room2, room3)) AS PivotedApts
以上是上述工作的SQLFiddle。
如果您要获得更多“房间”列,那么您可能需要考虑使用动态数据透视表,但由于没有查询计划,它们可能效率低下。
答案 1 :(得分:0)
1.您需要逐层使用Row_number()分区来获取行然后转动以获得您的要求
select p.floor,p.[1] as room1,p.[2] as room2,p.[3] as room3 from
(
select floor,apt,row_number() over(partition by floor order by apt) as rn from #t) as t
pivot
(
min(t.apt)
for t.rn in([1],[2],[3])
)as p;