I want to simplfy my T-SQL query. It is like this :
SELECT
t.a AS [Column A],
t.b AS [Column B],
t.c AS [Column C],
(t.a - t.b - t.c) AS [Column D],
CASE
WHEN (t.a - t.b - t.c) = 0 THEN 'Equals'
WHEN (t.a - t.b - t.c) > 0 THEN 'Greater'
WHEN (t.a - t.b - t.c) < 0 THEN 'Less'
END AS [Status]
FROM
Table1 AS t;
It would be nice to put (t.a - t.b - t.c)
into a variable, so I can reuse it on all places it occurs, because the expression may change over time.
I could not figure out how to do this without changing the existing query significantly.
You can use a CTE (Common Table Expression) like this:
This defines a CTE - something like a "ad-hoc" view - that you can use to handle things like calculations, aggregations etc. and then select from it (or use other SQL statements against it). The CTE only exists for the one, next statement - it doesn't get "persisted" for multiple SQL statements. But it's quite handy to handle situations like this