gpt4 book ai didi

sql-server - 我可以稍后在同一 View 中使用在 SQL Server View 中计算的列吗?

转载 作者:行者123 更新时间:2023-12-02 20:25:37 25 4
gpt4 key购买 nike

我可以稍后在同一 View 中使用在 SQL Server View 中计算的列吗?

假设我有以下观点:

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

有没有办法编辑 View 来执行以下操作

Select  
t1.StartMile, t2.EndMile, t2.EndMile - t1.StartMile as TotMile,
TotMile + 30 as EvenMoreMiles

我尝试了这个并收到错误:

Invalid column name 'TotMile'

请不要告诉我使用t2.EndMile - t1.StartMile + 30 作为 EvenMoreMilesTotMiles 是我实际代码中的一个很长的 case 语句。

我宁愿不必创建中间 View 。

我使用的是 SQL Server 2005。

稍后添加

谢谢大家的回答。我会全部投票。

这些答案提出了以下新问题:

鉴于有数千行,并且 TotMiles 如下所示,给出的答案中哪一个最有效?或者创建中间 View 是最有效的吗?

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,

最佳答案

您还可以使用更加简洁的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)

关于sql-server - 我可以稍后在同一 View 中使用在 SQL Server View 中计算的列吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8595709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com