SQL Statement to return a single record(s) creating multiple columns from a single column.
I have a table containing the following:
ID Value
ABC1 111
ABC1 222
ABC1 333
ABC2 111
ABC2 222
ABC2 333
Is there a way to get back the following result with a SQL statement?
ID Value Value Value
ABC1 111 222 333
ABC2 111 222 333
Thanks
Microsoft SQL ServerSQL
Last Comment
Qlemo
8/22/2022 - Mon
Rick_Rickards
SELECT Table1.ID, (SELECT T111.Value
FROM Table1 T111
WHERE (T111.ID = Table1.ID) AND (T111.Value="111");) AS 111, (SELECT T222.Value
FROM Table1 T222
WHERE (T222.ID = Table1.ID) AND (T222.Value="222");) AS 222, (SELECT T333.Value
FROM Table1 T333
WHERE (T333.ID = Table1.ID) AND (T333.Value="333");) AS 333
FROM Table1;
skinsfan99
ASKER
I don't think I was clear. First this table has thousands of records. The field names are ID and Value along with other data. I just need back a single recordset with 1 row for each ID with the Value fields as columns. I thought that you could do something where SQL would create a column array so the heading would look like:
There is a solution with fixed number of columns only, and it might perform bad:
select tbl1.ID, min(tbl1.Value), min(tbl2.Value), min(tbl3.Value)
from tbl tbl1
left join tbl tbl2 on tbl1.ID = tbl2.ID and tbl1.Value < tbl2.Value
left join tbl tbl3 on tbl2.ID = tbl3.ID and tbl2.Value < tbl3.Value
group by tbl1.ID
FROM Table1 T111
WHERE (T111.ID = Table1.ID) AND (T111.Value="111");) AS 111, (SELECT T222.Value
FROM Table1 T222
WHERE (T222.ID = Table1.ID) AND (T222.Value="222");) AS 222, (SELECT T333.Value
FROM Table1 T333
WHERE (T333.ID = Table1.ID) AND (T333.Value="333");) AS 333
FROM Table1;