简体   繁体   English

Oracle SQL按时间间隔分组

[英]Oracle SQL group by time interval

I have a table with the following columns: 我有一个包含以下列的表格:

order_number
customer_number
creation_date
estimated_ship_date

I need to select the max estimated_ship_date for any records with the same customer_number and the creation_date is within 15 minutes of each other. 我需要为具有相同customer_number的任何记录选择maximest_ship_date,并且creation_date彼此相隔15分钟以内。 It could be any number of records, 1-50 max I would say. 它可以是任意数量的记录,我会说最多1-50条。

So basically group by customer_number and creation_date within 15 minutes of each other. 因此,基本上可以在15分钟内按customer_number和creation_date进行分组。 It is the creation_date within 15 minutes of each other that I am stuck on. 我被困在彼此之间15分钟内的creation_date。

If you will only ever have to consider rows as a group if they all fall within a single 15 minute span then you could use a windowing clause : 如果您只需要将所有行都落在一个15分钟的跨度内而将它们视为一个组,则可以使用windowing子句

select order_number, customer_number, creation_date, estimated_ship_date,
  max(estimated_ship_date) over (partition by customer_number order by creation_date
    range between 15/1440 preceding and 15/1440 following) as estimated_ship_date
from cust_orders;

That gets each row of your table back with an additional column that shows the maximum ship date for any row fifteen minutes* either side of the current one. 这样一来,表格的每一行都会返回一个额外的列,该列显示当前行两边十五分钟*的任何行的最大发货日期。

It might not do quite what you want if you have a series of orders where each is within 15 minutes of the previous one, but they are not all within 15 minutes of all of the others - as in the example in my earlier comment. 如果您有一系列的订单,每个订单都在上一个订单的15分钟之内,但它们却不在所有其他订单的15分钟之内,那么它可能并没有达到您的期望-正如我之前的评论中的示例。 It sounds like you maybe don't expect that situation or wouldn't want to group them all together anyway, but you'd need to look at how the grouping worked if it did happen and maybe adjust it slightly. 听起来您可能不希望出现这种情况,或者不希望将它们归为一类,但是如果确实发生这种情况,则需要查看分组的工作方式,并可能对其进行一些调整。

* Oracle date arithmetic is based on 1 representing a full days, so 15 minutes is (15*60)/(24*60*60) seconds; * Oracle日期算术基于1代表一整天,因此15分钟为(15 * 60)/(24 * 60 * 60)秒; or 900/86400; 或900/86400; or 15/(24*60); 或15 /(24 * 60); or 15/1440; 或15/1440; or 1/96; 或1/96; etc. Which representation you use is a matter of taste and maintainability. 等。您使用哪种表示形式取决于口味和可维护性。 You can also use intervals if you prefer. 如果愿意,还可以使用间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM