这是我的表:
Site_name | date& Time | PowerOutput
----------+-------------------------+------------------
ACT0001 | 2013-07-21 01:00:00.000 | 196.852984494331
ACT0001 | 2013-07-21 02:00:00.000 | 0
xyz0001 | 2013-07-21 03:00:00.000 | 196.852984494331
xyq0001 | 2013-07-21 04:00:00.000 | 196.958395639561
xys0001 | 2013-07-21 05:00:00.000 | 0
xyd0001 | 2013-07-21 06:00:00.000 | 197.20098185022
xye0001 | 2013-07-21 07:00:00.000 | 0
xyg0001 | 2013-07-21 08:00:00.000 | 0
cfg0001 | 2013-07-21 09:00:00.000 | 197.412144323522
acb0001 | 2013-07-21 10:00:00.000 | 0
bdf0001 | 2013-07-21 11:00:00.000 | 0
olk0001 | 2013-07-21 12:00:00.000 | 196.886233049016
我有这张表,我正在尝试更新" ZERO"的地方的值。 如果只有一个零,那么我可以更新表,但如果有连续的零,我发现很难更新表。
逻辑是:
((先前值 - 下一个值)/前一个值)* 100 <5
如果这是真的那么它应该插入先前的值
((上一个值 - 下一个值)/前一个值)* 100&gt; = 5
如果这是真的那么它应该保持为零。
这是我到目前为止的代码:
with cte as
(
SELECT
*,
lead(pr_output,1) OVER (ORDER BY (select null)) As PreviousValue,
lag(pr_output,1) OVER (ORDER BY (select null)) As NextValue
FROM
[dbo].[Mytable]
)
,ctee as
(
select
*,
abs((PreviousValue*100-NextValue*100)/NextValue) as CheckFlag
from
cte
)
select
Site_name,[DATE&Time],
case
when pr_output <>0 then pr_output
else
case
when CheckFlag >= 5 then 0
else PreviousValue
end
end as pr_output
from
ctee
我得到的错误是
遇到零错误。
请告诉我我做错了什么。如果他们是通过这种方式的另一种方式吗?
感谢任何帮助。
输出应该是:Site_name | date& Time | PowerOutput
----------+-------------------------+------------------
ACT0001 | 2013-07-21 01:00:00.000 | 196.852984494331
ACT0001 | 2013-07-21 02:00:00.000 | 196.852984494331
xyz0001 | 2013-07-21 03:00:00.000 | 196.852984494331
xyq0001 | 2013-07-21 04:00:00.000 | 196.958395639561
xys0001 | 2013-07-21 05:00:00.000 | 196.958395639561
xyd0001 | 2013-07-21 06:00:00.000 | 197.20098185022
xye0001 | 2013-07-21 07:00:00.000 | 0
xyg0001 | 2013-07-21 08:00:00.000 | 0
cfg0001 | 2013-07-21 09:00:00.000 | 197.412144323522
acb0001 | 2013-07-21 10:00:00.000 | 0
bdf0001 | 2013-07-21 11:00:00.000 | 0
olk0001 | 2013-07-21 12:00:00.000 | 196.886233049016
答案 0 :(得分:0)
在除以之前需要检查NextValue是否为零..
希望这能解决你的问题。
with cte as
(
SELECT
*,
lead(pr_output,1) OVER (ORDER BY (select null)) As PreviousValue,
lag(pr_output,1) OVER (ORDER BY (select null)) As NextValue
FROM
[dbo].[Mytable]
)
,ctee as
(
select
*,
abs((PreviousValue*100-NextValue*100)/(case when NextValue = 0 then 1 else NextValue end)) as CheckFlag
from
cte
)
select
Site_name,[DATE&Time],
case
when pr_output <>0 then pr_output
else
case
when CheckFlag >= 5 then 0
else PreviousValue
end
end as pr_output
from
ctee