SQL问题:根据datediff从记录到记录获取记录
好吧,这里有一个棘手的问题...如果我的数据如下所示:
Table1
ID Date_Created
1 1/1/2009
2 1/3/2009
3 1/5/2009
4 1/10/2009
5 1/15/2009
6 1/16/2009
如何获取彼此相隔 2 天的记录? 我的最终结果集应该是第 1-3 行和第 5-6 行。 谢谢!
Ok, got a tricky one here... If my data looks like this:
Table1
ID Date_Created
1 1/1/2009
2 1/3/2009
3 1/5/2009
4 1/10/2009
5 1/15/2009
6 1/16/2009
How do I get the records that are 2 days apart from each other? My end result set should be rows 1-3, and 5-6. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
——这给了你什么?
从 table1 t1、table1 t2 选择 DISTINCT t1.id、t1.date_created、t2.id、t2.date_created 其中 datediff(dd,t1.date_created,t2.date_created) = 2 AND t1.id != t2.id ORDER BY t1 。ID;
-- what does this give you?
select DISTINCT t1.id, t1.date_created, t2.id, t2.date_created from table1 t1, table1 t2 where datediff(dd,t1.date_created,t2.date_created) = 2 AND t1.id != t2.id ORDER BY t1.id;
这行得通吗?
Would this work?
我可能建议使用编程代码来做到这一点。 您想要收集行组(单独的组)。 我认为您无法使用单个查询来解决此问题(这只会返回一组行)。
I might suggest using programming code to do it. You want to collect groups of rows (separate groups). I don't think you can solve this using a single query (which would give you just one set of rows back).
如果您想获取相隔“N”天内的行,您可以尝试以下操作:
例如,正如您所说,如果您想获取相隔 2 天的行,
您可以使用以下内容:
我希望这有帮助......
问候,
斯里克里希纳。
If you want to get the rows which are WITHIN 'N' days apart, you can try this:
for exmaple, as you said, if you want to get the rows which are WITHIN 2 days a part,
you can use the below:
I hope this helps....
Regards,
Srikrishna.
游标速度最快,但这里有一个 SELECT 查询可以做到这一点。 请注意,对于“最多 N”天而不是 2 天,您必须将表 Two 替换为 0 到 N-1 之间的整数表(并且效率会变差)。
我承认您并不完全清楚您想要什么,但我猜您想要的行范围总共包含至少两行,并且其中连续行最多相距 2 天。 如果日期随着 ID 一起增加,这应该可行。
A cursor will be fastest, but here is a SELECT query that will do it. Note that for "up to N" days apart instead of 2 you'll have to replace the table Two with a table of integers from 0 to N-1 (and the efficiency will get worse).
I'll admit it's not entirely clear what you want, but I'm guess you want the ranges of rows that contain at least two rows in all and within which the successive rows are at most 2 days apart. If dates increase along with IDs, this should work.