Re-use aliased field in SQL SELECT statement

前端 未结 2 1623
灰色年华
灰色年华 2020-12-11 02:15

I\'d like to achieve something like this:

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

Assuming that by \"...\" I\

相关标签:
2条回答
  • 2020-12-11 02:57

    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
    
    0 讨论(0)
  • 2020-12-11 03:03

    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.

    0 讨论(0)
提交回复
热议问题