Pivot Query is not converting all rows into columns

24 Views Asked by At

I wrote pivot query to convert rows of 'Service_Center' [column name] into columns, 'Service_Center' [column name] has three rows , two rows are namely ' Faisalabad ' and one is ' Gujranwala ' [city names] , in output it should convert these rows in column but it produces only 1 column of ' Gujranwala ' in output instead of ' Gujranwala ' and ' Faisalabad '.

 ` `DECLARE 
  @columns NVARCHAR(MAX) = '', 
  @sql     NVARCHAR(MAX) = '';

  **-- Select the distinct service center names**
  SELECT DISTINCT
  @columns = @columns + QUOTENAME(Service_Center) + ',' 
  FROM 
  #stock
  WHERE
  Service_Center IS NOT NULL AND PartCode IN (1947 , 1950,1962); 
  **--PartCode is the column name #stock**

  **-- Remove the last comma**
  SET @columns = LEFT(@columns, LEN(@columns) - 1);

  ** -- Construct dynamic SQL for the pivot operation**
  SET @sql ='
  SELECT * FROM   
  (
  SELECT
    SUM([GRN-Ito]) + SUM([GRN-PO]) + SUM([GRN-DIRECT]) + SUM([CN]) + SUM([ITO]) AS [Sum_GRN], 
    [Service_Center]
  FROM #stock
  WHERE Service_Center IS NOT NULL AND PartCode IN (1947,1950,1962)
  GROUP BY [Service_Center]
  ) t 
  PIVOT(
    MAX([Sum_GRN])
    FOR [Service_Center]
    IN ('+ @columns +')
   ) AS pivot_table;';

 **-- Execute the dynamic SQL**
  EXEC sp_executesql @sql;``
0

There are 0 best solutions below