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.
So this is the calculation:
(FLOOR(DATEPART(DAY, DATEADD(MINUTE, [table1].someInt, [table1].someDate)) / 1440.0) % 2) + 1
What it does is not important to this question. What matters is that this calculation is long to write.
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 SELECT statement, only in the JOIN and WHERE statements:
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
Now I would like to write this monstrosity above like this (by replacing all instances of the same calculation by a shorter name):
--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
Those two queries are the same, I just replaced the long calculation for the name/variable 'my_long_calculation'.
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?
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
select t1.id from (select *, my_long_calculation = floor(...) from table1) as t1 join table2 on table2.someattribute = t1.my_long_calculationetcmy_long_calculationin CTE (common table expression) and use in the main query.