我可以在同一视图中使用稍后在SQL Server视图中计算的列吗?
假设我有以下观点:
Select
t1.StartMile, t2.EndMile, t2.EndMile- t1.StartMile as TotMile
from
TableStarts as t1
inner join
TableEnds as t2 on t1.Id = t2.Id
有没有办法编辑视图以执行以下操作
Select
t1.StartMile, t2.EndMile, t2.EndMile - t1.StartMile as TotMile,
TotMile + 30 as EvenMoreMiles
我试过这个并收到错误:
无效的列名称“TotMile”
请不要告诉我使用t2.EndMile - t1.StartMile + 30 as EvenMoreMiles
。 TotMiles
是我实际代码中的长例语句。
我宁愿不必创建中间视图。
我正在使用SQL Server 2005。
稍后添加
感谢所有答案。我会全力以赴。
答案提出了以下新问题:
鉴于有数千行,TotMiles
如下所示,给出的答案中哪一个最有效?或者创建中间视图是否最有效?
CASE WHEN t .TaskType = 1 and t .StartTime < '1/1/2012'
THEN (tv.EndMile - tv.StartMile )
WHEN NOT (t .Location1_PKey = c.pkey OR t .Location2_PKey = c.pkey)
then (tv.EndMile - tv.StartMile )
WHEN (tv.EndMile - tv.StartMile ) < 31 Then 0
ELSE (tv.EndMile - tv.StartMile - 30 )
END AS MilesAdjusted2012,
答案 0 :(得分:9)
您还可以使用CROSS APPLY
,这可能更简洁,特别是如果您正在构建引用前面的别名链。
SELECT t1.StartMile,
t2.EndMile,
TotMile,
EvenMoreMiles,
AndYetMoreMiles
FROM TableStarts AS t1
INNER JOIN TableEnds AS t2
ON t1.Id = t2.Id
CROSS APPLY (SELECT t2.EndMile - t1.StartMile) A(TotMile)
CROSS APPLY (SELECT TotMile + 30) A2(EvenMoreMiles)
CROSS APPLY (SELECT EvenMoreMiles + 100) A3(AndYetMoreMiles)
答案 1 :(得分:3)
你不能直接,但你可以建立子选择:
select StartMile,EndMile,TotMile,TotMile+30 as EvenMoreMiles from (
Select t1.StartMile, t2.EndMile, t2.EndMile- t1.StartMile as TotMile
from
TableStarts as t1
inner join
TableEnds as t2
on t1.Id = t2.Id
) t
或使用公用表格表达式:
;with FirstCalcs as (
Select t1.StartMile, t2.EndMile, t2.EndMile- t1.StartMile as TotMile
from
TableStarts as t1
inner join
TableEnds as t2
on t1.Id = t2.Id
)
select StartMile,EndMile,TotMile,TotMile+30 as EvenMoreMiles from FirstCalcs
如果会有多个级别构建最终计算,我通常更喜欢使用CTE,因为否则大多数格式化方案很难做出选择,子选择,子子选择等等,这很容易阅读。 CTE可以包括对先前定义的CTE的引用:
;with CTE1 as (
SELECT ...
), CTE2 as (
SELECT ... FROM CTE1
), CTE3 as (
SELECT ... FROM CTE2
), CTE4 as (
SELECT ... FROM CTE2 ... CTE3
)
SELECT ... FROM CTE4 ... CTE1
答案 2 :(得分:1)
尝试使用派生表。
SELECT
DerivedTable.*,
TotMile + 30 as EvenMoreMiles
From (Select
t1.StartMile,
t2.EndMile,
t2.EndMile- t1.StartMile as TotMile
FROM Table t1
Inner Join table2 t2 on t1.PK = t2.FK) DerivedTable
答案 3 :(得分:1)
您可以使用公用表表达式(CTE)执行此操作。这里有很多:http://www.4guysfromrolla.com/webtech/071906-1.shtml
基本上,
CREATE VIEW ... AS
WITH Mileage (StartMile, EndMile, TotMile) AS (Select t1.StartMile, t2.EndMile, t2.EndMile- t1.StartMile as TotMile
from
TableStarts as t1
inner join
TableEnds as t2
on t1.Id = t2.Id)
SELECT TotMile FROM Mileage