我需要采取一些查询结果并将它们展平以获取报表。转换SQL查询结果
DECLARE @randomTable table (ID int, OtherID int, Val varchar(max))
insert into @randomTable(ID, OtherID, Val)
values (1, 100, 'Some Value 1'), (2, 100, 'Some Other 2'),
(3, 100, 'Some Value 3'), (4, 200, 'Some Other 4'),
(5, 200, 'Some Value 5'), (6, 300, 'Some Other 6'),
(7, 300, 'Some Value 7'), (8, 300, 'Some Other 8'),
(9, 400, 'Some Value 9'), (10, 500, 'Some Other 10')
select OtherID, Val from @randomTable
结果:
-- 100 | Some Value 1
-- 100 | Some Other 2
-- 100 | Some Value 3
-- 200 | Some Other 4
-- 200 | Some Value 5
-- 300 | Some Other 6
-- 300 | Some Value 7
-- 300 | Some Other 8
-- 400 | Some Value 9
-- 500 | Some Other 10
是否有一个SQL的方式来改变这种作为选择:
-- 100 | Some Value 1 | Some Other 2 | Some Value 3
-- 200 | Some Other 4 | Some Value 5
-- 300 | Some Other 6 | Some Value 7 | Some Other 8
-- 400 | Some Value 9
-- 500 | Some Other 10
注意:上面就是一个例子。我的真实数据不是静态的。此外,在我的真实数据中,OtherID
是一个字符串值,Val
值是以varbinary存储的图像。
我当然要限制我将允许的列数。我想最多5(在这之后,我很好,失去了额外的行)。
有没有办法做到这一点?
这正是我所需要的!谢谢马丁,你很乐意帮助我解决这个问题! – Vaccano 2011-03-27 03:51:09
Martin,非常聪明的使用rn分区! – 2011-03-27 04:18:40