日期范围内缺失的行数
我有一个具有以下结构的表
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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如评论中所建议的,创建一个包含感兴趣日期的表(我将其称为
datesofinterest
)。日期范围内的每个日期都需要放入此表中。然后,感兴趣日期表需要与所有用户 ID 相连接——这是感兴趣日期和用户 ID 的所有可能组合的集合。
现在,您必须删除原始表中当前的所有感兴趣日期/用户 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.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:
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)