简体   繁体   English

SQL从日期以及最低和最高值中选择不同的最低和最高记录

[英]SQL select distinct min and max records from date and lowest and highest values

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. 我尝试使用的是distinct(date),但是由于时间不同,它会返回所有结果。 I also tried Trunc but does not work. 我也尝试过Trunc,但没有用。

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

I'm using mySql 5.6 and this query works: 我正在使用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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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