Using an Alias in SQL Calculations
Why won't this query work?
SELECT 10 AS my_num, my_num*5 AS another_numb开发者_运维问答er
FROM table
In this example, I'm trying to use the my_num alias in other calculations. This results in unknown column "my_num"
This is a simplified version of what I am trying to do, but basically I would like to use an alias to make other calculations. My calculations are much more complicated and thats why it would be nice to alias it since I repeat it several times different ways.
Simply wrap your reused alias with (SELECT alias)
:
SELECT 10 AS my_num,
(SELECT my_num) * 5 AS another_number
FROM table
You'll need to use a subselect to use that aliases that way
SELECT my_num*5 AS another_number FROM
(
SELECT 10 AS my_num FROM table
) x
Aliases in sql are not like variables in a programming language. Aliases can only be referenced again at certain points (particularly in GROUP BY
and HAVING
clauses). But you can't reuse an alias in the SELECT
clause. So you can use a derived query (such as suggested by Rubens Farias) which lets you basically rename your columns and/or name any computed columns.
Or you could use a VIEW
if your formulas are generally fixed
CREATE VIEW table10 AS SELECT 10 AS my_num FROM table;
SELECT my_num * 5 AS another_number FROM table10;
I believe that will be slightly faster than using a derived query but it probably depends a lot on your real query.
Or you could just duplicate the work:
SELECT 10 AS my_num, 10 * 5 AS another_number FROM table;
Which might be convenient in something like php/perl:
my $my_num = 10;
my $query = "SELECT $my_num AS my_num, $my_num * 5 AS another_number FROM table";
``Another option is to use the APPLY operator
SELECT my_num, my_num*5 AS another_number
FROM table
CROSS APPLY
(SELECT 5 AS my_num) X
精彩评论