Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Pivot
Message
From
03/02/2017 12:50:01
John Baird
Coatesville, Pennsylvania, United States
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Title:
Re: Pivot
Miscellaneous
Thread ID:
01647435
Message ID:
01647442
Views:
41
>>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.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform