I need to take some query results and flatten them out for a report.
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
results:
-- 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
Is there an SQL way to change this to select as:
-- 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
NOTE: The above is an example. My real data is not static. Also, in my real data the OtherID
is a string value and Val
values are images stored as varbinary.
I would of course have to limit how many columns I am going to allow. I am thinking a max of 5 (after that I am fine to lose the extra rows).
Is there any way to do this?