选择IN的T sql数据透视表

时间:2015-09-02 06:52:08

标签: sql-server tsql pivot

我仅针对产品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

我还有产品表,如下所示

ProductID int

ProductName varchar(50)

问题:

我如何使用(我想从Product表中选择所有ProductID)

select ProductID from Product

如下

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 个答案:

答案 0 :(得分:0)

你必须使用DYNAMIC PIVOT这样的东西:

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