我需要一种方法来连接具有函数结果的表。我不确定这是否可能,不知怎的,我认为这不是一个好主意。让我试着解释一下情况。
有一个表[实体]:
[ID] [Description] [kWh] [kVArh] [kVAh] [OfferID] [CustomOfferID]
另一张表[数据]:
[ID] [Timestamp] [Value]
一个功能:
[Calc] (@offer, @customOffer, @kWh, @kVArh, @kVAh, @dtStart, @dtEnd)
所以你可以看到有实体,实体的数据(用法)和计算成本的函数。
我需要显示多个网站的使用情况和费用:
[Description] [MWh] [MVA] [Cost]
[MWh]
将是该期间所有实体数据的总和; [MVA]
将是该期间所有数据的最大值;并且[Cost]
将汇总子查询(函数)中的[Cost]
字段。
我认为可以完成这些工作的查询如下:
SELECT [tc].[ID], [tc].[Desc]
, SUM([kWh].[Value]) / 1000 AS [MWh]
, MAX([kVAh].[Value]) / 1000 AS [MVA]
, SUM([cost].[Cost])
FROM [Tree_Cost] AS [tc]
INNER JOIN [Data] AS [kWh] ON [tc].[kWh] = [kWh].[ID]
INNER JOIN [Data] AS [kVAh] ON [tc].[kVAh] = [kVAh].[ID]
INNER JOIN
(
SELECT [tc].[ID], [Cost]
FROM [Calc] ([tc].[Offer_ID], [tc].[OfferCustom_ID], [tc].[kWh], [tc].[KVArh], [tc].[kVAh], @dtStart, @dtEnd)
) AS [cost] ON [tc].[ID] = [cost].[ID]
WHERE [tc].[Type] = 1 AND [tc].[TypeDesc] = 'GF_K_M'
AND [kWh].[Timestamp] BETWEEN @dtStart AND @dtEnd
AND [kVAh].[Timestamp] BETWEEN @dtStart AND @dtEnd
GROUP BY [tc].[ID], [tc].[Desc]
这里真正的问题是我需要在内部查询(函数)的结果集中包含外部查询中的[ID]
,以便能够加入这两者。然后我还需要能够使用外部查询中的字段作为内部查询(函数)的参数。
这显然不是因为内部查询中无法识别[tc]
标识符。那么我该如何完成这样的事呢?
CREATE FUNCTION [dbo].[Calc]
( \@intOffer [int]
, \@intCustom [int]
, \@intP [int]
, \@intQ [int]
, \@intS [int]
, \@dtStart [datetime]
, \@dtEnd [datetime]
)
RETURNS TABLE
( [Entry] [nvarchar](200) NULL
, [Rate] [float] NULL
, [Unit] [nvarchar](50) NULL
, [Reading] [float] NULL
, [Cost] [float] NULL
, [DDate] [nvarchar](50) NULL
)
WITH EXECUTE AS CALLER
AS EXTERNAL NAME [OfferCalcLite].[UserDefinedFunctions].[SqlArray]
答案 0 :(得分:0)
我不确定我是否正确理解。也许你可以完全放弃JOIN:
INNER JOIN
(
SELECT [tc].[ID], [Cost]
FROM [Calc] ([tc].[Offer_ID], [tc].[OfferCustom_ID], [tc].[kWh], [tc].[KVArh], [tc].[kVAh], @dtStart, @dtEnd)
) AS [cost] ON [tc].[ID] = [cost].[ID]
并改变:
, SUM([cost].[Cost])
成:
, SUM( [Calc] ( [tc].[Offer_ID]
, [tc].[OfferCustom_ID]
, [tc].[kWh]
, [tc].[KVArh]
, [tc].[kVAh]
, @dtStart, @dtEnd
)
) AS Cost