日期范围内缺失的行数

发布于 2024-11-30 22:48:00 字数 537 浏览 1 评论 0原文

我有一个具有以下结构的表

 transaction_id    user_id     date_column   
   1                  1        01-08-2011     
   2                  2        01-08-2011    
   3                  1        02-08-2011   
   4                  1        03-08-2011

每个日期每个用户最多只能有一个条目。

如何获取特定日期范围内不存在 user_id 的所有行。 因此,对于上面带有 user_id= 2 和日期范围 01-08-2011 到 03-08-2011 的表,我想

result
02-08-2011
03-08-2011

现在,我正在使用 for 循环来循环给定日期范围内的所有日期。 这在小日期范围内工作得很好,但我认为对于大日期范围来说它会变得资源繁重。

I have a table with following structure

 transaction_id    user_id     date_column   
   1                  1        01-08-2011     
   2                  2        01-08-2011    
   3                  1        02-08-2011   
   4                  1        03-08-2011

There can be at-max only one entry for each user on each date.

How can get all rows where user_id is not present for specific date range.
So for above table with user_id= 2 and date range 01-08-2011 to 03-08-2011, I want

result
02-08-2011
03-08-2011

Right now, I am using for loop to loop over all dates in given date range.
This is working fine with small date range, but I think it will become resource heavy for large one.

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

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

发布评论

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

评论(1

猥︴琐丶欲为 2024-12-07 22:48:00

正如评论中所建议的,创建一个包含感兴趣日期的表(我将其称为datesofinterest)。日期范围内的每个日期都需要放入此表中。

datesofinterest table
--------------
date
--------------
01-08-2011
02-08-2011
03-08-2011

然后,感兴趣日期表需要与所有用户 ID 相连接——这是感兴趣日期和用户 ID 的所有可能组合的集合。

现在,您必须删除原始表中当前的所有感兴趣日期/用户 ID 才能获得最终答案。

在关系代数中,它会类似于:

(datesofinterest[date] x transaction[user_id]) - (transaction[date_column, user_id])

此页面可能有助于翻译 ' -' 到 SQL。 生成日期以填充datesofinterest表可以在 SQL 中手动或使用帮助程序完成 (perl 的日期时间)

As suggested in a comment, create a table with the dates of interest (I'll call it datesofinterest). Every date from your date range needs to be put into this table.

datesofinterest table
--------------
date
--------------
01-08-2011
02-08-2011
03-08-2011

Then the datesofinterest table needs to be joined with all the userids -- this is the set of all possible combinations of dates-of-interest and userids.

Now you have to remove all those dates-of-interest/userids that are currently in your original table to get your final answer.

In relational algebra, it'd be something like:

(datesofinterest[date] x transaction[user_id]) - (transaction[date_column, user_id])

This page may help with translating '-' to SQL. Generating dates to populate the datesofinterest table can be done in SQL, manually, or with a helper program (perl's DateTime)

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