我有这个查询
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
这些是结果:
正如您所看到的,我的一些列值为null
。如果值0
?
null
答案 0 :(得分:1)
这是一个简单的方法:
SELECT mto.LineId, mto.[LineNumber], round(sum(mto.Quantity), 3) as TotalNeed
v.*, (v.TotalMRC - v.TotalMIV ) as Shortage
FROM [SPMS2].[dbo].[ViewMTO] mto CROSS APPLY
(VALUES (ISNULL(SPMS2.dbo.ReturnTotalMRCByLineId(mto.LineId), 0),
ISNULL(SPMS2.dbo.ReturnTotalMIVByLineId(mto.LineId), 0),
ISNULL(SPMS2.dbo.ReturnTotalIMIVByLineId(mto.LineId), 0)
)
) v(TotalMRC, TotalMIV, TotalIMIV)
GROUP BY mto.lineid, mto.[LineNumber];
通常情况下,我更喜欢COALESCE()
到ISNULL()
(因为前者是标准的)。但是,COALESCE()
会对第一个参数进行两次计算。因此,对于昂贵的操作(例如用户定义的函数),ISNULL()
更有效。
答案 1 :(得分:1)
您可以使用coalesce
将null
替换为值:
SELECT LineId,
[LineNumber],
TotalNeed,
TotalMRC,
TotalMIV,
TotalIMIV,
(TotalMRC - TotalMIV) as Shortage
FROM (
SELECT LineId,[LineNumber],
round(sum(Quantity),3) as TotalNeed
,COALESCE(SPMS2.dbo.ReturnTotalMRCByLineId(LineId), 0) as TotalMRC
,COALESCE(SPMS2.dbo.ReturnTotalMIVByLineId(LineId), 0) as TotalMIV
,COALESCE(SPMS2.dbo.ReturnTotalIMIVByLineId(LineId), 0) as TotalIMIV
FROM [SPMS2].[dbo].[ViewMTO]
GROUP BY lineid,[LineNumber]
) a