Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-use aliased field in SQL SELECT statement

I'd like to achieve something like this:

SELECT 
  (CASE WHEN ...) AS FieldA,
  FieldA + 20 AS FieldB
FROM Tbl

Assuming that by "..." I've replaced a long and complex CASE statement, I don't want to repeat it when selecting FieldB and use the aliased FieldA instead.

Note, that this will return multiple rows, hence the DECLARE/SET outside the SELECT statement is no good in my case.

like image 238
Ruslan Avatar asked Mar 15 '10 11:03

Ruslan


People also ask

How do I use alias with same SELECT statement?

Alias is used to give a temporary name(only for the duration of the query) to the column or table in order to make the column name or table name more readable. It does not change the name of the column permanently. Alias can be performed using the 'AS' keyword or without any keyword.

Can we use alias in SELECT statement?

Table Alias. Table aliases can be used in SELECT lists and in the FROM clause to show the complete record or selective columns from a table. Table aliases can be used in WHERE, GROUP BY, HAVING, and ORDER BY clauses.

Can we add alias column in SQL query?

You can rename a table or a column temporarily by giving another name known as Alias. The use of table aliases is to rename a table in a specific SQL statement. The renaming is a temporary change and the actual table name does not change in the database.

Can you use alias in WHERE clause SQL?

In PROC SQL, a column alias can be used in a WHERE clause, ON clause, GROUP BY clause, HAVING clause, or ORDER BY clause. In the ANSI SQL standard and ISO SQL standard, the value that is associated with a column alias does not need to be available until the ORDER BY clause is executed.


2 Answers

A workaroud would be to use a sub-query:

SELECT
  FieldA,
  FieldA + 20 AS FieldB
FROM (
  SELECT 
    (CASE WHEN ...) AS FieldA
  FROM Tbl
) t

To improve readability you could also use a CTE:

WITH t AS (
  SELECT 
    (CASE WHEN ...) AS FieldA
  FROM Tbl
)
SELECT
  FieldA,
  FieldA + 20 AS FieldB
FROM
  t
like image 113
Peter Lang Avatar answered Nov 15 '22 16:11

Peter Lang


When I have complicated logic to compute a "virtual" column value from other column values in a table I generally create a single-table view of the original table with all the original columns plus the computed values as well. Then I do other SELECTs against the view. That allows me:

  1. To name my computed columns.

  2. To keep the logic for the computations in one place instead of scattered through various queries in the application.

like image 33
Larry Lustig Avatar answered Nov 15 '22 15:11

Larry Lustig