0

I get these errors:

Msg 156, Level 15, State 1, Line 22
Incorrect syntax near the keyword 'select'.

Msg 102, Level 15, State 1, Line 22
Incorrect syntax near ')'

when running this code:

Select * 
from 
    (select 
         DWF_Week_No
         ,DWF_Fuel_Name
         ,DWF_T_Sale 
     from 
         QF_FDashboard_Week_Fuel 
     where 
         DWF_Month_Name = 'October' 
         and DWF_Location_Name = 'Fitzroy') t
pivot
    (sum(DWF_T_Sale)
        for DWF_Fuel_Name in (select distinct DWF_Fuel_Name from QF_FDashboard_Week_Fuel)
    ) as pivot_table;
Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

0

It is not possible to put a SELECT inside the IN in the PIVOT. You can find a workaround here. In your case it would be something like this:

DECLARE @col nvarchar(max) = (stuff( ( select distinct  ',[' + Ltrim(rtrim(DWF_Fuel_Name)) +']' from QF_FDashboard_Week_Fuel FOR XML PATH('')),1,1,''))
    EXEC('Select * 
    from 
        (select 
             DWF_Week_No
             ,DWF_Fuel_Name
             ,DWF_T_Sale 
         from 
             QF_FDashboard_Week_Fuel 
         where 
             DWF_Month_Name = ''October'' 
             and DWF_Location_Name = ''Fitzroy'') t
    pivot
        (sum(DWF_T_Sale)
            for DWF_Fuel_Name in ('+@col+')
        ) as pivot_table;
    ')