你可以做到這一點
select top (1000)
Region,
calc.[Highest Students],
calc.[Highest Schools],
calc.[Average Students],
calc.[Average Schools],
dbo.fn_Calculator(calc.[Highest Students], calc.[Average Students]) as [Total Students],
dbo.fn_Calculator(calc.[Highest Schools], calc.[Average Schools]) as [Total Schools]
From myTable as t
outer apply (select
dbo.fn_Function1(Code, 2016) AS [Highest Students],
dbo.fn_Function2(Code, 2016) AS [Highest Schools],
dbo.fn_Function3(Code, 2016) AS [Average Students],
dbo.fn_Function4(Code, 2016) AS [Average Schools]
) as calc
但總的來說,@TimSchmelter是關於使用功能,如果避免完全正確有可能 - 標量函數通常對性能很差。在你的情況,你至少可以刪除fn_calculator
功能:
select top (1000)
Region,
calc.[Highest Students],
calc.[Highest Schools],
calc.[Average Students],
calc.[Average Schools],
calc.[Highest Students] + calc.[Average Students] as [Total Students],
calc.[Highest Schools] + calc.[Average Schools] as [Total Schools]
From myTable as t
outer apply (select
dbo.fn_Function1(Code, 2016) AS [Highest Students],
dbo.fn_Function2(Code, 2016) AS [Highest Schools],
dbo.fn_Function3(Code, 2016) AS [Average Students],
dbo.fn_Function4(Code, 2016) AS [Average Schools]
) as calc
你也可以使用一個CTE:
;with cte as (
select top (1000)
t.Region,
dbo.fn_Function1(Code, 2016) AS [Highest Students],
dbo.fn_Function2(Code, 2016) AS [Highest Schools],
dbo.fn_Function3(Code, 2016) AS [Average Students],
dbo.fn_Function4(Code, 2016) AS [Average Schools]
From myTable as t
)
select
c.Region,
c.[Highest Students],
c.[Highest Schools],
c.[Average Students],
c.[Average Schools],
dbo.fn_Calculator(c.[Highest Students], c.[Average Students]) as [Total Students],
dbo.fn_Calculator(c.[Highest Schools], c.[Average Schools]) as [Total Schools]
from cte as c
最有效的方法是避免這些功能。 –