选择日期间隔

发布于 2025-01-14 11:59:22 字数 1008 浏览 0 评论 0原文

可以选择记录之间预先定义的天数间隔,例如:

+------+----------------+--------+
| user | date           |  Data  |
+----- +----------------+--------+
|    1 | 2022-01-01     |   1    |
|    1 | 2022-01-02     |   5    |
|    1 | 2022-01-03     |   2    |
|    1 | 2022-01-06     |   3    |
|    1 | 2022-01-07     |   7    |
|    1 | 2022-01-08     |   1    |
|    1 | 2022-01-09     |   2    |
+------+----------------+--------+

GIVE ME ALL RECORDS WITH 2 DAYS INTERVAL FOR EACH DATE

(银行记录中可能存在间隙,因为发生在2022-01-032022-01-06之间)

结果:

+------+----------------+--------+
| user | date           |  Data  |
+----- +----------------+--------+
|    1 | 2022-01-01     |   1    |
|    1 | 2022-01-06     |   3    |
|    1 | 2022-01-09     |   2    |
+------+----------------+--------+

但是这个2天的值可以更改为7天, 30等

目前我正在通过代码手动执行此操作,我获取开始日期,添加+ x天,执行选择,添加+ x天,执行其他选择直到间隔结束,但这非常昂贵,并且该过程需要几分钟。

有没有办法在单个查询中做到这一点?

It is possible to make a selection with a pre-defined interval of days between records, ex:

+------+----------------+--------+
| user | date           |  Data  |
+----- +----------------+--------+
|    1 | 2022-01-01     |   1    |
|    1 | 2022-01-02     |   5    |
|    1 | 2022-01-03     |   2    |
|    1 | 2022-01-06     |   3    |
|    1 | 2022-01-07     |   7    |
|    1 | 2022-01-08     |   1    |
|    1 | 2022-01-09     |   2    |
+------+----------------+--------+

GIVE ME ALL RECORDS WITH 2 DAYS INTERVAL FOR EACH DATE

(There may be gaps in the records at the bank as happened between 2022-01-03 and 2022-01-06)

Result:

+------+----------------+--------+
| user | date           |  Data  |
+----- +----------------+--------+
|    1 | 2022-01-01     |   1    |
|    1 | 2022-01-06     |   3    |
|    1 | 2022-01-09     |   2    |
+------+----------------+--------+

But this value of 2 days can be changed to 7 days, 30 etc.

Currently I'm doing this manually by code, I get the start date, add + x days, do the select, add + x days, do the other select until the interval ends, but this is extremely expensive and the process takes minutes.

Is there any way to do this in a single query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铜锣湾横着走 2025-01-21 11:59:22
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY `date`) rn
    FROM tablename
)
SELECT * 
FROM cte
WHERE rn MOD 3 = 1
WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY `date`) rn
    FROM tablename
)
SELECT * 
FROM cte
WHERE rn MOD 3 = 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文