J'ai ce tableau:
PRODUCTNUMBER Stylecode FabricCategory LableCode 1020M Fashion NonQuilted LableCode
Je veux créer une requête pour me donner ce tableau
AttributeTypeName = Core Style --> TextValue Stylecode AttributeTypeName =Quilted/NonQuilted --> TextValue FabricCategory AttributeTypeName =Length/Weight --> TextValue LableCode
J'utilise case mais Je reçois 3 lignes pour chaque élément et je veux voir une seule ligne comme celle-ci
PRODUCTNUMBER AttributeTypeName TextValue 1020M Core Style Fashion 1020M Length/Weight LONG 1020M Quilted/NonQuilted NonQuilted
3 Réponses :
il suffit d'utiliser l'union de tous
select 'AttributeTypeName=',
max(case when AttributeTypeName='Core Style'
then TextValue end) from table
union all
select 'AttributeTypeName=',
max(case when AttributeTypeName='Quilted/NonQuilted'
then TextValue end) from table
union all
select 'AttributeTypeName=',
max(case when AttributeTypeName='Length/Weight'
then TextValue end) from table
Cela vous donnera des enregistrements redondants avec un tas de valeurs nulles
Vous pouvez essayer de rejoindre sur la même table
select a.PRODUCTNUMBER, d.TextVale StyleCode , b.TetValue FabricCategory, c.TextValue LabelCode
from (
select PRODUCTNUMBER, AttributeTypeName
from my_table
) a
left join my_table b on a.productnumber = b.productnumber
and b.AttributeTypeName ='Quilted/NonQuilted'
left join my_table c on a.productnumber = c.productnumber
and c.AttributeTypeName ='Length/Weight'
left join my_table d on a.productnumber = d.productnumber
and d.AttributeTypeName ='Core Style'
et si le premier attribut est également manquant
select a.PRODUCTNUMBER
, a.TextValue StyleCode
, b.TetValue FabricCategory
, c.TextValue LabelCode
from my_table a
left join my_table b on a.productnumber = b.productnumber
and b.AttributeTypeName ='Quilted/NonQuilted'
left join my_table c on a.productnumber = c.productnumber
and c.AttributeTypeName ='Length/Weight'
where a.AttributeTypeName ='Core Style'
Ah ... en utilisant LEFT JOIN au cas où les autres attributs seraient manquants. Et si le premier manquait?
Cela fonctionnera pour la plupart des bases de données, si votre liste ne contient que ces trois colonnes
SELECT PRODUCT_NUMBER,
MAX(CASE WHEN AttributeTypeName = 'Core Style' THEN TextValue ELSE NULL END) AS StyleCode,
MAX(CASE WHEN AttributeTypeName = 'Length/Weight' THEN TextValue ELSE NULL END) AS FabricCategory,
MAX(CASE WHEN AttributeTypeName = 'Quilted/NonQuilted' THEN TextValue ELSE NULL END) AS LableCode,
FROM TEST_DATA
GROUP
BY PRODUCT_NUMBER;
Quel SGBDR utilisez-vous? Cette opération s'appelle "pivoter" et se fait différemment selon ce que vous utilisez.