Skip to content
Loading
  • +2
    Hi
     
        After pivot calculation table structure will change. Hiw it can save in same #temp table. 
       
    Thanks 
    +2
  • +2
    Hi Amit
     
      It is not displaying Totals . Though it is inserting records in another table
     
    Thanks 
    +2
  • Amit Mohanty
    +2
    Hey, if you want total column in final table, then you have to modify your query to below query.
    1. DECLARE @cols AS NVARCHAR(MAX), @cols1 AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @columns VARCHAR(MAX);  
    2. SELECT @cols = COALESCE(@cols + ', ', '') + ItemName + ' = SUM(ISNULL([' + ItemName + '], 0))' FROM (SELECT DISTINCT ItemName FROM #temp) AS tmp  
    3. SELECT @cols1 = COALESCE(@cols1 + ', ', '') + ItemName FROM (SELECT DISTINCT ItemName FROM #temp) AS tmp  

    4. SELECT @columns = COALESCE(@columns + ', ', '') + '[' + ItemName + '] NUMERIC(19, 6)' FROM (SELECT DISTINCT ItemName FROM #temp) AS tmp    
    5. SET @columns = @columns + ', [total] NUMERIC(19, 6)'  
    6. IF OBJECT_ID('tempdb..#temp0') IS NOT NULL DROP TABLE #temp0      
    7. CREATE TABLE #temp0(Name NVARCHAR(100))    
    8. EXEC('ALTER TABLE #temp0 ADD ' + @columns)    

    9. DECLARE @cols2 AS NVARCHAR(MAX)  
    10. SELECT @cols2 = COALESCE(@cols2 + ' + ', '') + 'SUM(ISNULL([' + ItemName + '], 0))' FROM (SELECT DISTINCT ItemName FROM #temp) AS tmp  
    11. set @query = 'insert into #temp0 select Name, ' + @cols + ', total = ' + @cols2 + ' from (select name,quantity,itemname from #temp) x    
    12. pivot (Sum(quantity) for itemname in (' + @cols1 + ')) piv GROUP BY Name';    
    13. EXEC (@query)    
    14. SELECT * FROM #temp0 
    +2