我对SQL比较陌生,但在我身后有很好的编程经验。我有一段代码给我创建一个'Function',它将值返回到表中。但是,当代码试图比较2组数据以给出百分比差异时,我遇到了NULLS的问题。如果一组数据都是NULLS,则INSERT上不会发生Join,因此它不会返回任何内容,尽管实际上存在100%的差异。我想添加一个IF语句,这样如果其中一组数据的计数为零(它们都是空值),那么它默认一个值,如果有2个真正的数据集,那么它加入2并计算?希望这足以解释它。以下是大部分代码 - 如果没有数据,DS1VALS或DS2VALS可以不返回任何内容。我已经尝试了这个区域周围的所有东西来添加IF EXISTS或ISNULL,但没有任何作用。我确实得到一条消息,表明FUNCTION无法将答案返回给IF等??? 感谢。
-- get the PeriodicDataElementInstanceID for the datasources that we're using
select @DataSource1_PDEIID = PeriodicDataElementInstanceID
from PeriodicDataElementInstance
where Name = @DS1
select @DataSource2_PDEIID = PeriodicDataElementInstanceID
from PeriodicDataElementInstance
where Name = @DS2
-- get the start and end date of the periods in the past that we are checking.
-- these are based on the Calendar, calendar period type, and system start date set in the Universal
-- system options.
select @fromDate = StartDate
from dbo.GetPeriodsDateByPeriodsOffset(@X)
select @toDate = EndDate
from dbo.GetPeriodsDateByPeriodsOffset(@Y)
select @fromDate2 = StartDate
from dbo.GetPeriodsDateByPeriodsOffset(@XX)
select @todate2 = EndDate
from dbo.GetPeriodsDateByPeriodsOffset(@YY)
;with
DS1VALS (EI, Value) as
(select pds.EndItemID, sum(pd.value)
from PeriodicDataStream pds
join PeriodicData pd on pd.PeriodicDataStreamID = pds.PeriodicDataStreamID
where pds.PeriodicDataElementInstanceID = @DataSource1_PDEIID
and pd.PeriodDate between @fromDate and @todate
group by pds.EndItemID),
DS2VALS (EI, Value) as
(select pds.EndItemID, sum(pd.value)
from PeriodicDataStream pds
join PeriodicData pd on pd.PeriodicDataStreamID = pds.PeriodicDataStreamID
where pds.PeriodicDataElementInstanceID = @DataSource2_PDEIID
and pd.PeriodDate between @fromDate2 and @todate2
group by pds.EndItemID)
--select * from DS1VALS ds1
--join DS2VALS ds2 on ds1.EI = ds2.EI
Insert into @Results
select ds1.EI,
case
when (convert(numeric(19,9),ds1.Value) <> 0)
then (convert(numeric(19,9),ds2.Value) / convert(numeric(19,9),ds1.Value) - 1) * 100
else 9999999999
end
from DS1VALS ds1
join DS2VALS ds2 on ds1.EI = ds2.EI
where convert(numeric(19,9),ds1.Value) <> convert(numeric(19,9),ds2.Value);
Return
End
答案 0 :(得分:0)
我将假设以下内容:
从上面可以看出,如果任何一方为NULL,则将其视为零。您的解决方案是将NULL转换为零:
CASE
WHEN ISNULL(convert(numeric(19,9),ds1.Value), 0) = 0 THEN 9999999999
ELSE
(
ISNULL(convert(numeric(19,9),ds2.Value), 0)
/ convert(numeric(19,9),ds1.Value)
- 1
)
* 100
END
更新:根据反馈,以下内容也需要更改:
FROM DS1VALS ds1
FULL OUTER JOIN DS2VALS ds2 ON ds1.EI = ds2.EI
WHERE ISNULL(convert(numeric(19,9),ds1.Value), 0) <> ISNULL(convert(numeric(19,9),ds2.Value), 0);
请注意,加入现在是FULL OUTER JOIN
。这将匹配它可以的行,包括没有匹配右侧的左侧,以及左侧没有匹配的右侧。
您必须小心,WHERE
子句不会强制您的加入像INNER JOIN
一样工作。