使用sql删除零序列之前的时间序列
Posted
技术标签:
【中文标题】使用sql删除零序列之前的时间序列【英文标题】:Remove the time series before sequence of zero using sql 【发布时间】:2020-08-27 01:15:56 【问题描述】:我有一个时间序列如下:
Day. Data
1/1/2020. 0
2/1/2020 .2
3/1/2020 0
...... ...
1/2/2020 0
2/2/2020. 0
3/2/2020. .2
4/2/2020. .3
5/2/2020. 0
6/2/2020 0
7/2/2020. 0
8/2/2020 2
9/2/2020 2.4
10/2/2020 3
所以我希望过滤器数据仅显示在我们在时间序列中的最终零序列之后,在这种情况下,我只想获取 202 年 8 月 2 日之后的数据。 这个我试过了
SELECT * FROM table where Data> 0
结果如下:
Day. Data
2/1/2020 .2
...... ...
3/2/2020. .2
4/2/2020. .3
8/2/2020 2
9/2/2020 2.4
10/2/2020 3
但是这并没有找到lates 0 并删除之前的所有内容。
我还想在表格中按顺序显示最后一个零后 2 天的结果。
Day Data
10/2/2020 3
11/2/2020. 3.5
..... ....
【问题讨论】:
请用您正在运行的数据库标记您的问题:mysql、oracle、postgresql...? 我在雅典娜运行它我认为是postgresql 【参考方案1】:一种方法是:
select t.*
from t
where t.day > (select max(t2.day) from t t2 where t2.value = 0);
你可以抵消这个:
where t.day > (select max(t2.day) + interval '2' day from t t2 where t2.value = 0);
以上假设至少有一行有零。这里有两个简单的修复:
where t.day > all (select max(t2.day) from t t2 where t2.value = 0);
或:
where t.day > (select coalesce(max(t2.day), '2000-01-01') from t t2 where t2.value = 0);
【讨论】:
当你提到 max(t2.day) 是否意味着它将检查数据列以找到最大值? @user 。 . .子查询找到day
的最大值,其中值为0
。
是否也考虑序列?
@user 。 . .我不明白评论。它使用value = 0
拾取最后一行之后的所有行。【参考方案2】:
你可以使用窗口函数:
select day, data
from (
select t.*, max(case when data = 0 then day end) over() day0
from mytable t
) t
where day > day0 or day0 is null
order by day0
如果您想在最后一个 0
后两天开始,这很容易适应:
select day, data
from (
select t.*, max(case when data = 0 then day end) over() day0
from mytable t
) t
where day > day0 + interval '2 day' or day0 is null
order by day0
【讨论】:
当我运行代码时,它告诉我“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以获取在 '() day0 附近使用的正确语法”。因为我的日期栏是日期而不是日期,所以请告诉我如何解决它。我应该将day0更改为date0吗? over() 在 oracle 中,我使用的是 mysql 和 postgresql,因此它无法正常工作。 另外,当我使用 prstgresql 在 athena 中使用它时,它会告诉 Query 在这个比例因子下耗尽了资源 另一个问题是在间隔'2'天,天应该来自单qout间隔'2'天以上是关于使用sql删除零序列之前的时间序列的主要内容,如果未能解决你的问题,请参考以下文章