title: MSSQL Server Why group by alias doesn't work?
body: <p>I'm trying to solve the question in leetcode <a href="https://leetcode.com/problems/number-of-calls-between-two-persons/" rel="nofollow noreferrer">1699. Number of Calls Between Two Persons</a>. My solution doesn't work and it gives an error saying <code>[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'person1'. (207) (SQLExecDirectW)</code> How can I fix it?</p>
  <pre><code>SELECT 
      CASE 
          WHEN from_id &gt; to_id THEN to_id
          ELSE from_id
      END AS person1,
      CASE 
          WHEN from_id &gt; to_id THEN from_id
          ELSE to_id
      END AS person2,
      COUNT(duration) AS call_count,
      SUM(duration) AS total_duration
  FROM Calls
  GROUP BY person1, person2
  </code></pre>