Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Pivot
Message
De
03/02/2017 12:50:01
John Baird
Coatesville, Pennsylvanie, États-Unis
 
 
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Titre:
Re: Pivot
Divers
Thread ID:
01647435
Message ID:
01647442
Vues:
44
>>I have the following query:
>>
>>


>>SELECT fd.No,
>> fd.desc,
>> nf.nutDesc,
>> nd.nut_val
>> FROM fdes fd
>> inner join nutdata nd on nd.No = fd.No
>> inner join nutrdef nf on nf.No = nd.No
>>


>>
>>I get a lot of results can be up to 150. Here is a sample
>>
>>01001  Butter, salted   Protein  0.85
>>01001  Butter, salted   Total fat  81.11
>>01001  Butter, salted   Carbs  0.06
>>01001  Butter, salted   Ash  2.11
>>
>>How do I construct the query to yield them pivoted like this:
>>
>>No       Desc               Protein  Total fat  Carbs   Ash
>>01001 Butter, salted      0,85        81.11    0.06    2.11
>>
>>
>>I've looked at the pivot examples I find on the internet, but they make no sense...
>
>Do you want the Protein Total fat Carbs Ash be dynamic and descriptions? How should they be ordered?
>
>For your purpose you may want dynamic pivot.
>
>declare @Columns nvarchar(max), @Sql nvarchar(max);
>
>select @Columns = stuff((select ', ' + quotename(nutDesc) from (select distinct nutDesc from
>
> FROM fdes fd 
>	inner join nutdata nd on nd.No = fd.No
>	inner join nutrdef nf on nf.No = nd.No
>) X FOR XML PATH(''), type).value('.', 'nvarchar(max)'), 1,2,'')
>
>set @SQL = N'SELECT * FROM (SELECT fd.No, 
>fd.desc, 
>	nf.nutDesc,
>	nd.nut_val
> FROM fdes fd 
>	inner join nutdata nd on nd.No = fd.No
>	inner join nutrdef nf on nf.No = nd.No
>) X PIVOT (MAX(nut_Val) FOR NUT_DESC IN (' + @Columns + ')) pvt'
>
>PRINT @SQL;
>
>execute (@SQL)
>
>
>From the top of my head, so you may need to test and fix minor typos.

No, I need a dedicated list of 150 regardless if there's a value or not. IOW, They all have to appear in the pivot.
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform