Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using alias in the same select

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 ?

like image 648
phadaphunk Avatar asked May 17 '13 14:05

phadaphunk


People also ask

Can alias Use same SELECT statement?

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 := .

Can you reference an alias in SQL?

You can't reference an alias except in ORDER BY because SELECT is the second last clause that's evaluated.

Why can using an alias for a column in a SELECT statement be beneficial?

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.

Can you use aliases in WHERE clause?

The WHERE clause can contain non-correlated aliases and correlated aliases.


1 Answers

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
like image 194
Mahmoud Gamal Avatar answered Sep 22 '22 03:09

Mahmoud Gamal