Pivot sql convert rows to columns

前端 未结 2 1978
予麋鹿
予麋鹿 2021-01-26 08:03

The below query get the following out put.

Service Date  Product1 Product2 
01/Jun/2015    1           3
02/Jun/2015    2           5

Instead o

2条回答
  •  时光说笑
    2021-01-26 08:25

    Your current query is pivoting product names and grouping the dates. But you need to pivot the dates and group the product names

    Try this way

    DECLARE @cols  AS NVARCHAR(max),
            @query AS NVARCHAR(max)
    

    Find the distinct list of dates instead of product names

    SELECT @cols = Stuff((SELECT ','
                                 + Quotename(CONVERT(char(11), Service_Date, 106))
                          FROM   dbo.Store
                          WHERE  CatID = '2'
                          GROUP  BY CONVERT(char(11), Service_Date, 106)
                          ORDER  BY CONVERT(date, Service_Date)
                          FOR xml PATH (''), TYPE) .value('.', 'NVARCHAR(MAX)'), 1, 1, '')
    

    In pivot for list use the Service_date column instead of Product_Name

    SET @query = 'SELECT Product_Name,'
                 + @cols
                 + ' from ( select Service.Service_Date, Store.Product_Name, Servicelist.ProductQty FROM   dbo.Service INNER JOIN dbo.Servicelist ON dbo.Service.Service_ID = dbo.Servicelist.Service_ID INNER JOIN dbo.Store ON dbo.Servicelist.Pro_ID = dbo.Store.Pro_ID) x pivot ( SUM(ProductQty) for CONVERT(char(11), Service_Date, 106) in ('
                 + @cols + ') ) p '
    
    EXECUTE (@query); 
    

提交回复
热议问题