Once I set an a column name like this SUM(someColumn) AS [ColumnName]
, how can I use it afterwards ?
Let's say I build a query like this :
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
-- I need [TotalFooBar]
And in the same select I want the total of [TotalFoo]
and [TotalBar]
. Is it possible to refere to these columns ? I could do it the long way :
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
SUM((foo.A + foo.B + foo.C + foo.D + foo.E) +
(bar.A + bar.B + bar.C + bar.D + bar.E)) AS [TotalFooBar]
It's ok in this exemple but I have way more columns and it's hard to follow. And then what if I have to use this column ([TotalFooBar])? I'll have to rewrite the whole SUM everytime ?
What I'm looking for is something like this :
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
SUM([TotalFoo] + [TotalBar]) AS [TotalFooBar]
Is it even possible ?
No there isn't a way to refer to aliases, but you can assign the expression to a variable, and then refer to the variable in the same select clause. Inside a select statement variable assignment is always done by the infix operator := .
You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated.
Benefits of SQL AliasesAllows you to provide more readable names to the column headers when they're presented in the results. Allows client applications to refer to a calculated field by name where no column name exists. Allows you to reduce code and make your queries more concise.
The WHERE clause can contain non-correlated aliases and correlated aliases.
No, you can't do this in the same SELECT
statement, but you can use subquery:
SELECT
TotalFoo,
TotalBar,
TotalFoo + TotalBar AS TotalFooBar
FROM
(
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
...
FROM ...
) AS sub
...
or a CTE:
WITH CTE
AS
(
SELECT SUM(foo.A + foo.B + foo.C + foo.D + foo.E) AS [TotalFoo],
SUM(bar.A + bar.B + bar.C + bar.D + bar.E) AS [TotalBar],
...
FROM ...
)
SELECT
TotalFoo,
TotalBar,
TotalFoo + TotalBar AS TotalFooBar
FROM CTE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With