title: How to use Order by in Pivot Table using SQL Server
body: <p>I am using SQL Server 2008, and make below query for Pivot Table, </p>
  
  <pre><code>SELECT [pay date], 
         [adm. fee], 
         [colleege dev.] 
  FROM   (SELECT 
         CONVERT(VARCHAR(10), CONVERT(DATE, dbo._feepayment._issuedate, 106), 105) AS [Pay Date], 
         dbo._feehead._feeheadname AS aaa, 
         Isnull(dbo._feepaymentdet._amount, 0) AS _AMOUNT 
          FROM   dbo._feepaymentdet 
                 LEFT OUTER JOIN dbo._feehead 
                              ON dbo._feepaymentdet._feeheadid = 
                                 dbo._feehead._feeheadid 
                 RIGHT OUTER JOIN dbo._feepayment 
                               ON dbo._feepaymentdet._feepaymentid = 
                                  dbo._feepayment._feepaymentid 
          WHERE  ( dbo._feehead._isdeleted = N'1' ) 
                 AND ( dbo._feepayment._isdeleted = N'1' ) 
                 AND ( dbo._feepaymentdet._isdeleted = N'1' ) 
                 AND dbo._feepayment._issuedate &gt;= 
                     CONVERT(DATETIME, '01.09.2014 00:00:00', 105) 
                 AND dbo._feepayment._issuedate &lt;= 
                     CONVERT(DATETIME, '11.09.2014 23:59:59', 105)) AS s 
         PIVOT ( Sum(s._amount) 
               FOR s.aaa IN ( [ADM. FEE], 
                              [COLLEEGE DEV.] ) ) pvt 
  </code></pre>
  
  <p>Above query return following records,</p>
  
  <pre><code>Pay Date        ADM. FEE     COLLEEGE DEV.
  09-09-2014      25.00        100.00
  05-09-2014      75.00        300.00
  01-09-2014      25.00        100.00
  03-09-2014      75.00        310.00
  02-09-2014      50.00        200.00
  </code></pre>
  
  <p>but i want <code>ORDER BY</code> on Pay Date above record , if I add </p>
  
  <pre><code>WHERE (dbo._FEEHEAD._ISDELETED = N'1') 
   AND (dbo._FEEPAYMENT._ISDELETED = N'1') 
   AND (dbo._FEEPAYMENTDET._ISDELETED = N'1')  
   AND dbo._FEEPAYMENT._ISSUEDATE &gt;= CONVERT(DATETIME, '01.09.2014 00:00:00', 105) 
   AND dbo._FEEPAYMENT._ISSUEDATE &lt;= CONVERT(DATETIME, '11.09.2014 23:59:59', 105)
   ORDER BY dbo._FEEPAYMENT._ISSUEDATE 
  </code></pre>
  
  <p>SQL giving me Error :</p>
  
  <pre><code>The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries,
   and common table expressions, unless TOP or FOR XML is also specified.
  </code></pre>
  
  <p>How I add ORDER BY in above query .</p>