Comment convertir des lignes avec des valeurs distinctes en colonnes?

J'ai une table temporaire table1 comme ci-dessous

 table1 +------+---------------+------------+ | Id | Description | Atsortingbute | +------+---------------+------------+ | 1 | blue | color | | 1 | Large | size | | 1 | active | status | | 2 | green | color | | 2 | small | size | | 2 | inactive | status | +------+---------------+------------+ 

Je voudrais returnner une table comme ci-dessous:

 +------+-----------+-----------+-----------+ | Id | Color | Size | Status | +------+-----------+-----------+-----------+ | 1 | blue | large | active | | 2 | green | small | inactive | +------+-----------+-----------+-----------+ 

Y a-t-il un moyen de faire cela? Je vous remercie.

Utilisez PIVOT comme ci-dessous:

 DECLARE @Tbl TABLE (Id INT, Description NVARCHAR(max), Atsortingbute NVARCHAR(50)) INSERT INTO @Tbl select 1 , 'blue', 'color' union all select 1 , 'Large', 'size' union all select 1 , 'active', 'status' union all select 2 , 'green', 'color' union all select 2 , 'small', 'size ' union all select 2 , 'inactive', 'status' SELECT * FROM ( SELECT * FROM @Tbl ) A PIVOT ( MIN(Description) FOR Atsortingbute IN ([color], [size], [status] ) ) B 

Résultat:

 Id color size status 1 blue Large active 2 green small inactive 

Essayez d'utiliser

 Select a.id, (select max(b.description) from table1 b where b.id=a.id and b.atsortingbute='color') color, (select max(c.description) from table1 c where c.id=a.id and c.atsortingbute='size') size, (select max(d.description) from table1 d where d.id=a.id and d.atsortingbute='status') status from table1 a group by a.id 

Je ne l'ai pas encore lancé, mais pour votre exigence, cela devrait fonctionner. Mais si vous avez plus d'attributes, alors vous devriez opter pour un pivot dynamic.

 select case when c.id is not null then c.id when s.id is not null then s.id else st.id end as id ,c.color as color ,s.size as size ,st.status as status from (select id,description as color from table1 where atsortingbute='color') c full outer join (select id,description as Size from table1 where atsortingbute='size') s on c.id=s.id full outer join (select id,description as status from table1 where atsortingbute='status') st on c.id=st.id 

C'est simple avec PIVOT :

 SELECT * FROM table1 PIVOT (MAX(Description) FOR Atsortingbute IN (Color, Size, Status)) Pvt