title: SQL Server Pivot and Sort
body: <p>I have a shop order table with the Item code, description ReleaseDate and Required quantity. 
  How to query in a pivot table format in such a way that the results will be pivoted using Year+Month of [ReleaseDate] in sorting order from oldest date to latest date. Using the Year+Month as a column.</p>
  
  <p>This is my query but it fails.</p>
  
  <pre><code> --Declare necessary variables
  DECLARE   @SQLQuery AS NVARCHAR(MAX)
  DECLARE   @PivotColumns AS NVARCHAR(MAX)
  
  --Get unique values of pivot column  
  SELECT   @PivotColumns = COALESCE(@PivotColumns + ',','') + QUOTENAME([YEARMONTH]) 
  FROM (SELECT DISTINCT  CONVERT(char(6), cast([releaseddate] as date), 112 ) as [YEARMONTH] FROM [dbo].[ShopOrder]) as PivotQuery
  
  SELECT   @PivotColumns
  
  --Create the dynamic query with all the values for 
  --pivot column at runtime
  
  SET   @SQLQuery = 
      N'SELECT ItemCode, ' +   @PivotColumns + '
      FROM [dbo].[ShopOrder] 
      PIVOT( SUM(RequiredQty) 
            FOR [releaseddate] IN (' + @PivotColumns + ')) AS P'
  
  SELECT   @SQLQuery
  --Execute dynamic query
  EXEC sp_executesql @SQLQuery
  </code></pre>
  
  <p>This is the original record</p>
  
  <p><img src="https://i.stack.imgur.com/La3ym.png" alt="image"></p>
  
  <p>Results query must be like this</p>
  
  <p><img src="https://i.stack.imgur.com/nC3lY.png" alt="image"></p>