There is a database with online store customers, which has the following data:
- id buyer’s;
- order number;
- date and time of the order;
- order amount.
Data on customers and orders for 3 months.
How to withdraw customers who made more than 1 order per day and in the range of 3 hours of any day.
Is it possible to do this with a single query, or is it necessary to check each three-hour range manually?
For example, the buyer id 10321630 made 5 orders, on May 26, in the period from 19:00 to 22:00 (19:15, 19:37, 19:51, 21:07, 21:18) It is necessary that it be in the output of the query result.
I found tips on the Internet only about "between", but this is not exactly the case
3
Answers
BETWEEN
is the case. You can apply it to the::time
of what I’m guessing is your purchase timestamp: demo at db<>fiddleIf you mean any continuous 3-hour period within any one day, not the specific times between 19:00 and 20:00 from your example, it’s a bit trickier: you’ll need a stepping/rolling/tumbling count, which means using
count(*)
as a window function to restrict it to counting things up to3 hours
prior to any row.Problem with that is you might get overlaps, some of which you can get rid of using the
distinct on
above, to only keep the maximum period spanning from a common point, instead of listing all its sub-periods.If you have one order at midnight, another one at
2:59
and another one at4:58
, the middle one will show up once paired up with midnight and another time paired up with4:58
.this query will return what you want but I wrote it for MYSQL
the idea is grouping by
buyer_id
and the day of theorder_date
(without time)