简体   繁体   中英

Mysql query to establish group dates on daily records

i have a table with day_date and price each record is displayed as below:

Day_date   Price
2012-05-20 500
2012-05-21 500
2012-05-22 500
2012-05-23 600
2012-05-24 600
2012-05-25 500
2012-05-26 500
2012-05-27 700
2012-05-28 700

what i want to do is display as follow:

season 2012-05-20 to 2012-05-22 price 500
season 2012-05-23 to 2012-05-24 price 600
season 2012-05-25 to 2012-05-26 price 500
season 2012-05-27 to 2012-05-28 price 700

I am trying to do this using the following query below:

SELECT min(day_add) as start_date, max(day_add) as end_date, price 
FROM table GROUP BY price

With this query i get the following result:

2012-05-20  2012-05-26  500
2012-05-23  2012-05-24  600
2012-05-27  2012-05-28  700

as you see compared what i want to do is that the first record with price=500 should be from 20 to 22 of May 2012 and then on 3rd place should come 25 to 26 may wich the price=500 .

Since i am grouping by price it's cutting the season from 25 to 26 may 2012.

Is it possible to do SELECT to get the results as i want?

thanks

The problem is not with the query itself but with the data, as there is no value to group by. All you have to do is to create that new value.

You can do that this way:

select min(day_date) minDate, max(day_date) maxDate, price from (
  select day_date, @row := @row + (@price != price) grp, @price := price price
  from t, (select @row := 0, @price := '') init
  order by day_date
) final
group by final.grp, price

Here you have the fiddle to play with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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