计算缺失行的值

时间:2014-12-30 13:55:14

标签: sql missing-data

我有一个SQL查询,每天检索预测。如果某个给定的" LP"我想根据其他预测来计算它。但是,使用下面的代码时,它不会在缺失时计算预测。

agreementStart,agreementEnd和plantType属于tbl_p。我尝试将所有内容移动到ON部分,但随后包含其他行,这些行不应该存在,并且仍然没有计算缺失值。对于当前示例,结果集中包含缺少的行,但字段hour00_01,hour01_02,hour02_03保持为空,因为它们未计算。这些列的计算应该是这样的,如果id 1的hour00_01是1,id 2的hour00_01是2而id 3的hour00_01是null,那么id 3的id hour00_01应该是3(id 1和2的总和)

有人能指出我正确的方向:

declare @startDt date = '2014-12-19' declare @endDt date = '2014-12-19' ; with AllDates as 
( select @startDt as dt union all select dateadd(day, 1, dt) 
from AllDates where dateadd(day, 1, dt) <= @endDt ) 
select dt, m.date, p.lp, p.electricityArea, maxCapacity, SUM(maxCapacity) as c, p.netArea, 
CASE hour00_01 WHEN null THEN maxCapacity*(sum(hour00_01)/sum(maxCapacity)) ELSE hour00_01 END hour00_01, 
CASE hour01_02 WHEN null THEN maxCapacity*(sum(hour01_02)/sum(maxCapacity)) ELSE hour01_02 END hour01_02,
CASE hour02_03 WHEN null THEN maxCapacity*(sum(hour02_03)/sum(maxCapacity)) ELSE hour02_03 END hour02_03
from AllDates ad cross join tbl_p p LEFT JOIN tbl_m m
on p.lp = m.lp and m.date = ad.dt and m.inputType = 'TYPE' where p.plantType = '2' AND (agreementStart <= '2014-12-19' AND agreementEnd >= '2014-12-19')
   GROUP BY 
      ad.dt,
      m.date, 
      p.lp, 
      p.electricityArea, 
      maxCapacity, 
      p.netArea, 
      p.electricityArea, 
      hour00_01, hour01_02, hour02_03

1 个答案:

答案 0 :(得分:0)

问题出在你的WHERE条款中。您的agreementStartagreementEnd列属于哪个表格尚不清楚,但由于您对这些列和plantType列有条件,因此您拒绝任何NULL列(即在LEFT JOIN中没有匹配)。因此,请考虑将所有WHERE标准移动到ON - 连接的一部分:

. . .
from AllDates ad cross join tbl_p p LEFT JOIN tbl_m m
on p.lp = m.lp and m.date = ad.dt and m.inputType = 'TYPE' AND p.plantType = '2' AND (agreementStart <= '2014-12-19' AND agreementEnd >= '2014-12-19')
GROUP BY 
...