title: SQL Server - Set and use variable within select statement
body: <p>I have a SQL Server query with a calculation that I would like to call 'my_long_calculation' which I use in several places within my query. The problem is that I do not know how this 'my_long_calculation' calculation can be stored into a variable for easier readability.</p>
  
  <p>So this is the calculation: </p>
  
  <pre><code>(FLOOR(DATEPART(DAY, DATEADD(MINUTE, [table1].someInt, [table1].someDate)) / 1440.0) % 2) + 1
  </code></pre>
  
  <p>What it does is not important to this question. What matters is that this calculation is long to write.</p>
  
  <p>Now I use this same calculation in several places within the query like this (Don't try to understand it, just note that there are several places where I use the same calculation, but I don't use it in the <code>SELECT</code> statement, only in the <code>JOIN</code> and <code>WHERE</code> statements:</p>
  
  <pre><code>SELECT
      [table1].ID
  FROM 
      [table1]
  INNER JOIN 
      [table2] ON [table2].someattribute = (FLOOR(DATEPART(DAY, DATEADD(MINUTE, [table1].someInt, [table1].someDate)) / 1440.0) % 2) + 1
  INNER JOIN 
     [table3] ON [User].someattribute = (FLOOR(DATEPART(DAY, DATEADD(MINUTE, [table1].someInt, [table1].someDate)) / 1440.0) % 2) + 1
  WHERE 
      (FLOOR(DATEPART(DAY, DATEADD(MINUTE, [table1].someInt, [table1].someDate)) / 1440.0) % 2) + 1 = 1
  </code></pre>
  
  <p>Now I would like to write this monstrosity above like this (by replacing all instances of the same calculation by a shorter name):</p>
  
  <pre><code>--my_long_calculation = (FLOOR(DATEPART(DAY, DATEADD(MINUTE, [table1].someInt, [table1].someDate)) / 1440.0) % 2) + 1
  
  SELECT
      [table1].ID
  FROM 
      [table1]
  INNER JOIN 
      [table2] ON [table2].someattribute = my_long_calculation
  INNER JOIN 
      [table3] ON [User].someattribute = my_long_calculation
  WHERE 
      my_long_calculation = 1
  </code></pre>
  
  <p>Those two queries are the same, I just replaced the long calculation for the name/variable 'my_long_calculation'. </p>
  
  <p>The second statement, of course, throws an error because 'my_long_calculation' is not defined. But how can I define and set a variable within a query in order to improve readability? </p>
  
  <p>IMPORTANT: I don't want to return the long calculation by including it in the select statement. I only want to use it on the join and where statements</p>