title: Order by clause with distinct
body: <p>I have a table in sql server in which I have some values. For example as below,</p>
  
  <pre><code>StationId
  -----
  3
  11
  4
  </code></pre>
  
  <p>I have written a query as below,</p>
  
  <pre><code>select  STUFF((SELECT distinct (',' + QuoteName(c.StationId))
              FROM Analytics c 
              FOR XML PATH(''), TYPE
              ).value('.', 'NVARCHAR(MAX)')
          ,1,1,'') 
  </code></pre>
  
  <p>where output as below:</p>
  
  <pre><code>[11],[3],[4]
  </code></pre>
  
  <p>Now my requirement is I need the output as <code>[3],[4],[11]</code>. So when rewrite the query as</p>
  
  <pre><code>select  STUFF((SELECT distinct (',' + QuoteName(c.StationId))
              FROM Analytics c ORDER BY c.StationId 
              FOR XML PATH(''), TYPE
              ).value('.', 'NVARCHAR(MAX)')
          ,1,1,'')
  </code></pre>
  
  <p>I am getting below exception</p>
  
  <blockquote>
    <p>ORDER BY items must appear in the select list if SELECT DISTINCT is specified.</p>
  </blockquote>
  
  <p>Please give me some suggestions.</p>