SQL从日期,最低和最高值中选择不同的最小和最大记录

时间:2018-03-06 18:17:30

标签: php mysql date

假设我有一张这样的表:

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

我想检索不同的日期,并为每个不同的日期检索其第一个结果(如最低小时)及其相关价格和最新结果(如最高小时)及其相关价格。 我还需要检索每个不同日期的最高价和最低价。

是否可以通过单个查询执行此操作?如果有,怎么样? 我尝试使用distinct(日期),但由于有不同的小时数,它会返回所有结果。我也试过Trunc但是没有用。

Sample result:
date        min_price   max_price   lowest_hour_price   highest_hour_price
2018-03-06  $10         $18         $18                 $10

1 个答案:

答案 0 :(得分:0)

我正在使用mySql 5.6,这个查询有效:

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');