SQL:在查询的其他部分引用计算列

时间:2014-04-06 15:05:15

标签: sql sql-server sql-server-2012

我想在SQL Server 2012中执行以下操作:

SELECT UnitPrice * Quantity as SubTotal,
       SubTotal * (1-0.13) as Tax,
       Tax + SubTotal as Total
FROM Invoice

据我所知,这是不可能的,如上所述,但我想知道是否有一种特殊的方法可以在运行中识别列,可以在查询的其他地方引用,例如"字段列表" (SELECT子句的一部分),作为WHERE子句的一部分或在ORDER BY子句中。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

部分解决方案(在许多情况下已足够) 构造:

with Query as (
  select SubTotal as SubTotal,
         SubTotal * (1 - 0.13) as Tax,
         SubTotal * (1 - 0.15) as AnotherTax -- etc.
    from Invoice
)

select SubTotal,
       Tax,
       Tax + SubTotal as Total
  from Query

答案 1 :(得分:1)

您可以在cross apply

中进行计算
select T1.SubTotal,
       T2.Tax,
       T2.Tax + T1.SubTotal as Total
from Invoice as I
  cross apply (select I.UnitPrice * I.Quantity) as T1(SubTotal)
  cross apply (select T1.SubTotal * (1 - 0.13)) as T2(Tax)

SQL Fiddle