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.
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.
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.
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.
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.
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
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:
To name my computed columns.
To keep the logic for the computations in one place instead of scattered through various queries in the application.
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