1

I have below query for pivot table only for products 0 , 3 , 11

SELECT *
FROM (
    SELECT 
        year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID, 
        cp.salesprice as Amount 
    FROM customer_products cp

) as s
PIVOT
(
    SUM(Amount)
FOR [product_Id] IN ([0],[3],[11]) -- for 0 , 3 , 11 products
)AS a

I have also Product table as below

ProductID int

ProductName varchar(50)

Question:

How can i use ( I want to select all ProductID from Product table)

select ProductID from Product

as below

SELECT *
    FROM (
        SELECT 
            year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID, 
            cp.salesprice as Amount 
        FROM customer_products cp

    ) as s
    PIVOT
    (
        SUM(Amount)
FOR [product_Id] IN (select ProductID from Product) -- How can ı select all product ID here as select * from Product ?
    )AS a

1 Answers1

0

You have to use DYNAMIC PIVOT something like this:

DECLARE @cols   AS NVARCHAR(MAX) = '',
        @sql    AS NVARCHAR(MAX)

SELECT @cols += N'' + QUOTENAME(ProductID) + ', '
FROM   (
        SELECT DISTINCT ProductID
        FROM Product                         
        ) a                         
SET @cols   = LEFT(@cols, LEN(@cols) - 1)
SET @sql    = N'SELECT * FROM 
                (
                    SELECT 
                        year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID, 
                        cp.salesprice as Amount 
                    FROM customer_products cp               
                ) x 
                PIVOT
                (
                    SUM(Amount)
                    FOR [product_Id] IN (' + @cols + ') 
                ) p

EXEC Sp_executesql @sql