Reputation: 165
Let's say i have a table like this:
id | date | price
-------------------------------
1 | 2018-03-06 22:19:10 | $10
2 | 2018-03-06 13:16:19 | $12
3 | 2018-03-06 00:12:11 | $18
4 | 2018-03-05 23:29:10 | $10
5 | 2018-03-05 03:16:19 | $05
6 | 2018-03-05 00:11:11 | $11
I want to retrieve distinct date , and for each distinct date its first result (like lowest hour) and its related price and the latest result (like highest hour) and its related price. I also need to retrieve the highest and lowest price for each distinct date.
Is it possible doing this with a single query? If yes, how? What I tried is using distinct(date) but, since there are different hours, it returns all the results. I also tried Trunc but does not work.
Sample result:
date min_price max_price lowest_hour_price highest_hour_price
2018-03-06 $10 $18 $18 $10
Upvotes: 1
Views: 518
Reputation: 12684
I'm using mySql 5.6 and this query works:
select date(m.min_max_date) as date,
max(case when m.lbl='min_hr_price' then m.min_max_hr_price else null end) as lowest_hr_price,
max(case when m.lbl='max_hr_price' then m.min_max_hr_price else null end) as max_hr_price,
max(case when n.lbl='min_price' then n.min_max_price else null end) as min_price,
max(case when n.lbl='max_price' then n.min_max_price else null end) as max_price
from (select 'min_hr_price' as lbl, price as min_max_hr_price, date as min_max_date
from tbl
where date in (select min(date) as min_date from tbl group by date(date))
union
select 'max_hr_price', price, date
from tbl
where date in (select max(date) as max_date from tbl group by date(date))) as m,
(
select 'min_price' as lbl,
min(date) as min_max_date,
min(price) as min_max_price
from tbl
group by date(date)
union
select 'max_price' as lbl,
max(date) as min_max_date,
max(price) as min_max_price
from tbl
group by date(date)
) n
where m.min_max_date=n.min_max_date
group by date(m.min_max_date)
order by m.min_max_date
Sample result:
date lowest_hr_price max_hr_price min_price max_price
2018-03-06 $1102.8 $1821 $1011.6 $1821
INSERT INTO TBL VALUES(1, '2018-03-06 22:19:10', '$1011.6');
INSERT INTO TBL VALUES(2, '2018-03-06 13:19:11', '$1011.6');
INSERT INTO TBL VALUES(3, '2018-03-06 03:21:25', '$1106.2');
INSERT INTO TBL VALUES(4, '2018-03-06 00:26:50', '$1102.8');
INSERT INTO TBL VALUES(5, '2018-03-06 22:26:17', '$1821');
Upvotes: 1