Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select data and grouping data by date range

Tags:

sql

mysql

I have table with data like this

price date type
1000 2021-03-13 A
1000 2021-03-14 A
1000 2021-03-15 A
1300 2021-03-16 A
1000 2021-03-17 A
1300 2021-03-18 A
1000 2021-03-19 A
1500 2021-03-20 A
1500 2021-03-21 A
1500 2021-03-22 A
2000 2021-03-13 B
2000 2021-03-14 B
2000 2021-03-15 B
2000 2021-03-16 B
2000 2021-03-17 B

I want to query data like this

price startDate endDate type
1000 2021-03-13 2021-03-15 A
1300 2021-03-16 2021-03-16 A
1000 2021-03-17 2021-03-17 A
1300 2021-03-18 2021-03-18 A
1000 2021-03-19 2021-03-19 A
1500 2021-03-20 2021-03-22 A
2000 2021-03-13 2021-03-17 B

my current sql below but it is not correct at all

SELECT MIN(date) as startDate, MAX(date) as endDate, price, type                                      
                            FROM prices 
                            GROUP BY type, price
                            ORDER BY type, MIN(date)
like image 845
banku Avatar asked Jun 05 '26 20:06

banku


1 Answers

This is a gaps and islands problem, and one simple way to handle it uses the difference in row numbers method. Assuming you are using MySQL 8+, the following should work:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY type ORDER BY date) rn1,
              ROW_NUMBER() OVER (PARTITION BY type, price ORDER BY date) rn2
    FROM prices
)

SELECT price, MIN(date) AS startDate, MAX(date) AS endDate, type
FROM cte
GROUP BY price, type, rn1 - rn2
ORDER BY type, startDate;

screen capture from demo link below

Demo

like image 62
Tim Biegeleisen Avatar answered Jun 08 '26 14:06

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!