如何使用开始日期和结束日期(SQL)获取每个日期一行?

发布于 2025-01-15 21:03:47 字数 486 浏览 0 评论 0原文

我是 SQL 新手,想知道是否有人可以帮助我提出查询。

我需要从这里开始:

在此处输入图像描述

对此:

在此处输入图像描述

基本上,我有一个包含一些类标签及其开始和结束日期的表格。我想在开始日期和结束日期之间每个日期有一行。我尝试在 SQL 中查找一些日期函数,并且知道我可能必须在某些时候使用 DATEADD,在开始日期中添加天数,直到到达结束日期。除此之外,我很困难,希望得到任何帮助!谢谢

I'm new to SQL and was wondering if someone can help me come up with a query.

I need to go from this:

enter image description here

To this:

enter image description here

Basically, I have a table with some class labels and their start and end dates. I would like to have one row per date between the start and end dates. I have tried looking up some date functions in SQL and know I probably have to use DATEADD at some point, to add days to the start date until we reach the end date. Beyond this I am pretty stuck and would appreciate any help with this! Thanks

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

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

发布评论

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

评论(1

妄想挽回 2025-01-22 21:03:47

我将使用递归 cte 来构建日期序列并将其连接到您的类表中。类似 -

with recursive date_range (date) AS (
    select min(start_date) from t
    union all
    select date(date + interval '1day') from date_range where date + interval '1day' <= (select max(end_date) from t)
)
select t.*, dr.*
from date_range dr
join t
    on dr.date between t.start_date and t.end_date
order by t.class, dr.date

这是一个 db<>fiddle

I would use a recursive cte to build up the date sequence and join it to your class table. Something like -

with recursive date_range (date) AS (
    select min(start_date) from t
    union all
    select date(date + interval '1day') from date_range where date + interval '1day' <= (select max(end_date) from t)
)
select t.*, dr.*
from date_range dr
join t
    on dr.date between t.start_date and t.end_date
order by t.class, dr.date

Here's a db<>fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文