Skip to content
Advertisement

Need help in framing SQL Query

TABLE-1

OrderDate CustomerNo ProductId Quantity
2021-03-01 1 1 10
2021-03-01 1 3 20
2021-03-02 1 2 15
2021-03-02 1 3 10
2021-03-03 1 1 10
2021-03-03 1 5 25

This table also contains data for other customers also Customers 2,3,4 …

TABLE-2

ProductId ProductName
1 P1
2 P2
3 P3
4 P4
5 P5

Products are not Fixed, may be added P6,P7 …

RESULT :

OrderDate P1 P2 P3 P4 P5
2021-03-03 10 25
2021-03-02 15 10
2021-03-01 10 20

I need this result , is this possible using Pivot / UnPivot

Advertisement

Answer

Here is the dynamic PIVOT for the query
DECLARE @SQL  AS VARCHAR(MAX)
, @cols_ AS  vARCHAR(MAX) 

--Making the column list dynamically 
SELECT @cols_   = STUFF((SELECT DISTINCT ', '+QUOTENAME(  [T2].[ProductName]) 
               FROM  [TABLE_2] [T2]                
               FOR XML PATH('')), 1, 1, '')              


print @cols_
--preparing PIVOT query dynamically. 

SET @SQL = ' SELECT
       pivoted.* 
      into #Temp_data
      FROM 
      (
    SELECT 
         [T1].[OrderDate],           
         [T2].[ProductName], 
         SUM([T1].[Quantity] ) AS  [Quantity]
    FROM [TABLE_1] [T1] 
    INNER JOIN [TABLE_2] [T2] 
      ON [T1].[ProductId] =  [T2].[ProductId]
    GROUP BY  [T1].[OrderDate],              
         [T2].[ProductName] 
      ) AS [p]
      PIVOT
      (
         MIN([P].[Quantity]) 
         FOR  [P].[ProductName]  IN (' + @cols_ + ')
      ) AS pivoted;



      select *        
       from #Temp_data [B]
      -- GROUP BY [B].[OrderDate]  

      drop table #Temp_data
   ';

   PRINT( @SQL)
   EXEC (@SQL)

Result: Dynamic PIVOT

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement