T-SQL列由两列派生

时间:2017-10-10 08:37:14

标签: sql sql-server tsql

假设有这个查询:

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

当我写(ColDerA - ColDerB) AS ColDerC SQL时返回此错误:
Invalid column name 'ColDerA'ColDerB相同) 如何创建ColDerC列?

感谢。

2 个答案:

答案 0 :(得分:2)

使用嵌套查询

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

答案 1 :(得分:0)

原因是SQL从上到下(当你阅读代码时)不能以普通方式工作,因此对于用户而言,在用别名命名列之后可能很明显,别名可以在同一个中使用查询。不幸的是,SQL首先以批处理方式执行查询,因此为了使用查询返回的任何结果,您需要将其包装在子查询(嵌套查询)中。因此,您必须像这样使用它:

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