sql server使用计算列

时间:2011-11-15 11:38:38

标签: sql sql-server-2008

我有这样的查询:

select 
(price1 + price2 + price3) as total_price 
from prices

如何使用计算列total_price来计算其他总数?<​​/ p>

select 
(price1 + price2 + price3) as total_price,
(price4 + total_price) as total_price2
from prices    

这可能吗?

3 个答案:

答案 0 :(得分:11)

否则无法引用在同一级别定义的列别名。出现在同一逻辑查询处理阶段的表达式为evaluated as if at the same point in time

As Joe Celko says

  

事情在SQL中“一下子”发生,而不是“从左到右”   将在顺序文件/程序语言模型

您可以在CTE中定义它,然后在CTE外重复使用它。

实施例

WITH T
     AS (SELECT ( price1 + price2 + price3 ) AS total_price,
                price4
         FROM   prices)
SELECT total_price,
       ( price4 + total_price ) AS total_price2
FROM   T  

答案 1 :(得分:3)

如果经常使用

,我还会在桌面上考虑computed column
ALTER  TABLE prices ADD
   total_price AS (price1 + price2 + price3)

然后您的查询

select 
    total_price,
    (price4 + total_price) as total_price2
from prices

这样,您可以应用DRY原则......

答案 2 :(得分:1)

select T.total_price,
       P.price4 + T.total_price as total_price2
from prices as P
  cross apply (select P.price1 + P.price2 + P.price3) as T(total_price)