title: ORDER BY ROW_NUMBER
body: <p>UPD: thanks for all, topic closed, after sleeping I understand everything =)</p>
  
  <p>I have a problem with understanding OVER clause and and ROW_NUMBER function. Simple table - name and mark. I want to calculate average mark for each name.</p>
  
  <pre><code>SELECT top 1 with ties name,  ROW_NUMBER() over (PARTITION BY name ORDER BY name) as number
  FROM table 
  ORDER BY AVG(mark) OVER(PARTITION BY name)
  </code></pre>
  
  <p>it will display something like this, and I understand why - that is what ROW_NUMBER() does</p>
  
  <pre><code>name|number
  Pete 1
  Pete 2
  </code></pre>
  
  <p>But if I write</p>
  
  <pre><code>SELECT top 1 with ties name,  ROW_NUMBER() over (PARTITION BY name ORDER BY name) as number
  FROM table 
  ORDER BY AVG(mark) OVER(PARTITION BY name), number
  </code></pre>
  
  <p>it will display</p>
  
  <pre><code>name|number
  Pete 1
  </code></pre>
  
  <p>And this time I don't understand how ORDER BY works with ROW_NUMBER() function. Can somebody explain it to me?</p>