Avatar of skinsfan99
skinsfan99
Flag for United States of America asked on

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

Avatar of undefined
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:

ID        Value(0)      Value(1)    Value(2)  
ABC1   111               222             333
ABC2   111               222             333
Qlemo

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



This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Qlemo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Qlemo

any news?