SELECT
LineId, [LineNumber],
ROUND(SUM(Quantity), 3) AS TotalNeed,
SPMS2.dbo.ReturnTotalMRCByLineId(LineId) AS TotalMRC,
SPMS2.dbo.ReturnTotalMIVByLineId(LineId) AS TotalMIV,
SPMS2.dbo.ReturnTotalIMIVByLineId(LineId) AS TotalIMIV,
(TotalMRC-TotalMIV ) AS Shortage
FROM
[SPMS2].[dbo].[ViewMTO]
GROUP BY
lineid, [LineNumber]
但我收到了这些错误:
Msg 207,Level 16,State 1,Procedure LineMaterialStatus,Line 10
列名称“TotalMRC”无效。Msg 207,Level 16,State 1,Procedure LineMaterialStatus,Line 10
列名称“TotalMIV”无效。
我的问题是我们可以使用'as'作为变量来保存SQL Server中的值吗?
答案 0 :(得分:4)
此问题的正常解决方案是使用CTE或子查询。
我想指出SQL Server有另一种方法outer apply
:
SELECT mto.LineId, mto.[LineNumber], round(sum(mto.Quantity), 3) as TotalNeed
v.*, (v.TotalMRC - v.TotalMIV ) as Shortage
FROM [SPMS2].[dbo].[ViewMTO] mto OUTER APPLY
(VALUES (SPMS2.dbo.ReturnTotalMRCByLineId(mto.LineId),
SPMS2.dbo.ReturnTotalMIVByLineId(mto.LineId),
SPMS2.dbo.ReturnTotalIMIVByLineId(mto.LineId)
)
) v(TotalMRC, TotalMIV, TotalIMIV)
GROUP BY mto.lineid, mto.[LineNumber];
答案 1 :(得分:1)
只需使用子查询即可实现此目的:
SELECT LineId,
[LineNumber],
TotalNeed,
TotalMRC,
TotalMIV,
TotalIMIV,
(TotalMRC - TotalMIV) as Shortage
FROM (
SELECT LineId,[LineNumber],
round(sum(Quantity),3) as TotalNeed
,SPMS2.dbo.ReturnTotalMRCByLineId(LineId) as TotalMRC
,SPMS2.dbo.ReturnTotalMIVByLineId(LineId) as TotalMIV
,SPMS2.dbo.ReturnTotalIMIVByLineId(LineId) as TotalIMIV
FROM [SPMS2].[dbo].[ViewMTO]
GROUP BY lineid,[LineNumber]
) a
您可以选择第一个语句的输出作为第二个语句的源子查询,这样您就可以使用您创建的计算列。
然后,您只需将(TotalMRC - TotalMIV) as Shortage
移至外部查询,然后可以使用计算列。