我有一个编码问题,我希望这里有一些经验丰富的人可以帮助我。
我希望创建以下结果。它基于分钟数据。我有一个关于' ConditionA'的专栏。和' ConditionB'。我试图检测哪些时候' ConditionB'在条件A'之后发生。我需要在每天结束时重置它。
DATETIME ConditionA ConditionB Detected
2017-10-31 15:55:00.000 0 0 0
2017-10-31 15:56:00.000 1 0 0
2017-10-31 15:57:00.000 1 0 0
2017-10-31 15:58:00.000 1 0 0
2017-10-31 15:59:00.000 0 0 0
2017-10-31 16:00:00.000 0 1 1
2017-10-31 16:01:00.000 0 1 0
2017-10-31 16:02:00.000 0 1 0
2017-10-31 16:03:00.000 0 0 0
2017-10-31 16:04:00.000 1 0 0
2017-10-31 16:05:00.000 1 0 0
2017-10-31 16:06:00.000 0 0 0
2017-10-31 16:07:00.000 0 0 0
2017-10-31 16:08:00.000 0 1 1
2017-10-31 16:09:00.000 0 1 0
2017-10-31 16:10:00.000 0 1 0
2017-10-31 16:11:00.000 0 0 0
2017-10-31 16:12:00.000 0 1 0
2017-10-31 16:13:00.000 0 1 0
2017-10-31 16:14:00.000 0 1 0
2017-10-31 16:15:00.000 0 0 0
2017-10-31 16:16:00.000 0 1 0
2017-10-31 16:17:00.000 0 0 0
2017-10-31 16:18:00.000 0 0 0
2017-10-31 16:19:00.000 1 0 0
2017-10-31 16:20:00.000 1 0 0
2017-10-31 16:21:00.000 1 0 0
2017-10-31 16:22:00.000 0 0 0
2017-10-31 16:23:00.000 0 0 0
2017-10-31 16:24:00.000 1 0 0
2017-10-31 16:25:00.000 0 1 1
2017-10-31 16:26:00.000 0 1 0
我已经为此工作了一个星期并一直在旋转我的车轮。我考虑过CTE,虽然循环但是我一直无法解决这个问题。有人会介意我指出哪种方法最终会起作用的正确方向?如果我知道这一点,我可以尝试一下,如果需要可以提出进一步的问题。
谢谢,
答案 0 :(得分:3)
看起来您只想查看B
1
的位置,而前一个值不是0
。如果是这样的话:
select t.*,
(case when b = 1 and lag(b) over (order by datetime) = 0
then 1 else 0
end) as detected
from t;
答案 1 :(得分:0)
谢谢戈登,你的回答让我得到了解决方案。它应该如下:
select t.*,
(case when b = 1 and lag(b) over (order by datetime) = 0
then 1 else 0
end) as detected
from t
where not (a = 0 AND b = 0);
通过where子句删除具有零的条件的行允许它按照需要工作。