1

I wrote this query to generate pivot table :

SELECT *
FROM (
    SELECT 
        ItemName_AR as [ItemName], 
        NetValue as Amount 
    FROM view_WH_CompanyTransactionDtl
) as s
PIVOT
(
    SUM(Amount)
    FOR [ItemName] IN (select ItemName_AR from WH_Items)
)AS pvt

but it cuases the following error in

Incorrect syntax near the keyword 'select'.

at this statment

FOR [ItemName] IN (select ItemName_AR from WH_Items)
Raed Alsaleh
  • 1,581
  • 9
  • 27
  • 50

2 Answers2

2

Unfortunately, you may not use a select statement to provide the variety of values (unpivoted form)=columns(pivoted form). You may either use IN ([value1],[value2]) etc or consider a dynamic solution, here's a link: SQL Server Dynamic Pivot Column Names

George Menoutis
  • 6,894
  • 3
  • 19
  • 43
0

You cannot create Dynamic SQL PIVOT like that. You may try something like this...

DECLARE @cols AS NVARCHAR(max) = Stuff((SELECT DISTINCT ',' + Quotename(ItemName_AR)
         FROM   WH_Items       
         FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''); 

DECLARE @query AS NVARCHAR(max) =  'SELECT *
                                    FROM (
                                        SELECT 
                                            ItemName_AR as [ItemName], 
                                            NetValue as Amount 
                                        FROM view_WH_CompanyTransactionDtl
                                    ) as s
                                    PIVOT
                                    (
                                        SUM(Amount)
                                        FOR [ItemName] IN ('+ @cols +')
                                    )AS pvt';

EXECUTE(@query) 
DxTx
  • 3,049
  • 3
  • 23
  • 34