SQL-如何在两个值之间计数行?
我有一个SQL表,其中包含时间戳和相关的值。看起来像这样:
Original_table:
TIMESTAMP | 值 |
---|---|
2022-06-03 00:09:15.000 | 75 |
:09:16.000 | 0 |
2022-06-06-03 00:09:09: | 2022-06-03 00 |
19.000 :29.000 | 12 |
2022-06-03 00:09:44.000 | 0 |
2022-06-03 00:09:55.000 | 5 |
2022-06-06-03 00:09:56.000 | 0 |
我试图制作一个像这样的桌子包含在timestamp_start字段中的值== 0的行。在Timestamp_end字段中,它包含下一个值不等于0的时间戳记:
wanty_table:
timestamp_start | timestamp_end |
---|---|
2022-06-03 00:09:16.000 | 2022-06-06-06-03 00:09:09:09:29.000 |
2022-06-06-06-06-06-06-06-06-06-06-06-06-06-06-06-06-06-03 00 :09:44.000 | 2022-06-03 00:09:55.000 |
2022-06-06-03 00:09:56.000 | null |
*** null ***编辑***最后一个,timestamp_end必须为空(null),因为之后有0 。
我尝试使用
coalesce(lead(timeStamp,SELECT COUNT(*)
FROM ORIGINAL_TABLE
WHERE value=0
的行数吗
它仅计算值== 0有任何提示 ?谢谢!
I have an SQL table that contains timestamp and value associated. It looks like this :
ORIGINAL_TABLE:
timestamp | value |
---|---|
2022-06-03 00:09:15.000 | 75 |
2022-06-03 00:09:16.000 | 0 |
2022-06-03 00:09:19.000 | 0 |
2022-06-03 00:09:29.000 | 12 |
2022-06-03 00:09:44.000 | 0 |
2022-06-03 00:09:55.000 | 5 |
2022-06-03 00:09:56.000 | 0 |
I am trying to make a table like this one, where it only contains the rows where value==0 in the timestamp_start field. In the timestamp_end field, it contains the timestamp of the next value that is not equal to 0:
WANTED_TABLE :
timestamp_start | timestamp_end |
---|---|
2022-06-03 00:09:16.000 | 2022-06-03 00:09:29.000 |
2022-06-03 00:09:44.000 | 2022-06-03 00:09:55.000 |
2022-06-03 00:09:56.000 | NULL |
***EDIT *** For the last one, timestamp_end has to be empty (NULL) because there is 0 after.
I tried using
coalesce(lead(timeStamp,SELECT COUNT(*)
FROM ORIGINAL_TABLE
WHERE value=0
However it only counts the number of rows where value == 0
Any tips ? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道您正在使用什么DB。但是我在PostgreSQL中写了此SQL查询,我认为此查询将在许多数据库中运行。
结果:
I don't know what DB you are using. But I wrote this SQL query in PostgreSQL, I think that this query will be run in many Databases.
Result: