如何在一个MysQl查询中找到MIN,MAX,FIRST,LAST?

时间:2018-04-27 06:59:42

标签: mysql

我有一张如下表格

products

 id  price  date 
-------------------------------
 1    1     2018-04-27 12:10:15
 2    2     2018-04-27 12:10:15
 3    5     2018-04-27 12:10:18
 4    3     2018-04-27 12:10:18
 5    4     2018-04-27 12:11:25
 6    3     2018-04-27 12:11:25

注意:我必须找到最低价格,最高价格,起始价格,每分钟的结束价格。

我的预期输出是

firstPrice lastPrice minPrice maxPrice
---------------------------------------
    1          3         1       5     --> Grouped for (2018-04-27 12:10)
    4          3         3       4     --> Grouped for (2018-04-27 12:11)

我的查询是

SELECT b.lastPrice,c.firstPrice,min(a.price) as minPrice,max(a.price) as maxPrice from products as a left join (select price as lastPrice,date from products order by date desc) as b on a.date = b.date left join (select price as firstPrice,date from products order by date asc) as c on a.date = c.date where a.date >= '2018-04-27 12:10:00'

我不知道如何获得预期的输出。

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

SELECT 
    (SELECT price FROM products WHERE DATE_FORMAT(p.`date`, '%Y%m%d%H%i') = DATE_FORMAT(`date`, '%Y%m%d%H%i') ORDER BY `date` ASC, id ASC LIMIT 1) AS firstPrice,
    (SELECT price FROM products WHERE DATE_FORMAT(p.`date`, '%Y%m%d%H%i') = DATE_FORMAT(`date`, '%Y%m%d%H%i') ORDER BY `date` DESC, id DESC LIMIT 1) AS lastPrice,
    MIN(price) AS minPrice, MAX(price) AS maxPrice 
FROM products p 
GROUP BY DATE_FORMAT(`date`, '%Y%m%d%H%i')
  

演示: http://sqlfiddle.com/#!9/8a989/15/0

答案 1 :(得分:0)

这可能是使用限制条款在子查询中获取第一个和最后一个价格并按日期分组的。

drop table if exists t;
create table t(id int,  price int , dt datetime);
insert into t values
( 1  ,  1  ,   '2018-04-27 12:10:15'),
( 2  ,  2  ,   '2018-04-27 12:10:15'),
( 3  ,  5  ,   '2018-04-27 12:10:18'),
( 4  ,  3  ,   '2018-04-27 12:10:18'),
( 5  ,  4  ,   '2018-04-27 12:11:25'),
( 6  ,  3  ,   '2018-04-27 12:11:25');


select concat(date(dt),' ',hour(dt), ':',minute(dt) ,':00') Timeslot,
         (select price from t t1 where concat(date(t1.dt),' ',hour(t1.dt), ':',minute(t1.dt) ,':00') = concat(date(t.dt),' ',hour(t.dt), ':',minute(t.dt) ,':00') order by id limit 1) firstprice,
         (select price from t t1 where concat(date(t1.dt),' ',hour(t1.dt), ':',minute(t1.dt) ,':00') = concat(date(t.dt),' ',hour(t.dt), ':',minute(t.dt) ,':00') order by id desc limit 1) lastprice,
         min(price),max(price)
from t
group by concat(date(dt),' ',hour(dt), ':',minute(dt) ,':00');

+---------------------+------------+-----------+------------+------------+
| Timeslot            | firstprice | lastprice | min(price) | max(price) |
+---------------------+------------+-----------+------------+------------+
| 2018-04-27 12:10:00 |          1 |         3 |          1 |          5 |
| 2018-04-27 12:11:00 |          4 |         3 |          3 |          4 |
+---------------------+------------+-----------+------------+------------+
2 rows in set (0.00 sec)