简体   繁体   中英

T-SQL column derived by two columns

Suppose to have this query:

SELECT ((ColumnA*ColumnB)/ColumnC) AS ColDerA
       ,(ColumnD + ColumnE - ColumnF) AS ColDerB
       ,(ColDerA - ColDerB) AS ColDerC
FROM TableA

When I write (ColDerA - ColDerB) AS ColDerC SQL return this error:
Invalid column name 'ColDerA' (same for ColDerB ).
How do I create ColDerC column?

Thanks.

Use a nested query

SELECT ColDerA, ColDerB, (ColDerA - ColDerB) AS ColDerC
FROM
(
   SELECT ((ColumnA*ColumnB)/ColumnC) AS ColDerA
        ,(ColumnD + ColumnE - ColumnF) AS ColDerB
  FROM TableA
) t

The reason is that SQL doesn't work in ordinary fashion, from top to bottom (as you read the code), so for user it might be obvious that after naming columns with aliases, the aliases can be used in the same query. Unfortunately not, SQL first executes the query as a batch, so in order to use any results that the query returned, you need to wrap it in subquery (nested query). Therefore, you have to use it like this:

SELECT ColDerA, ColDerB, ColDerA - ColDerB FROM (
SELECT ((ColumnA*ColumnB)/ColumnC) AS ColDerA
   ,(ColumnD + ColumnE - ColumnF) AS ColDerB
   --,(ColDerA - ColDerB) AS ColDerC --this would work, if you had used directly columns from the table: ((ColumnA*ColumnB)/ColumnC) - (ColumnD + ColumnE - ColumnF)
FROM TableA ) AS A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM