只获取列中的最大值和最小值-sql

wlzqhblo  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(440)

这里我提到了一个数据,我只想将max和min date值作为一行提取到我的新表中。

ID   date        Comment grade
    1   12-Jul-2013 asdads  1
    1   2-Apr-2014  dfgdfg  1
    1   29-Dec-2014 ghjghj  2
    10  8-Oct-2015  cbvcvb  1
    10  10-Jan-2017 sdfsdf  5
    10  29-May-2018 ertert  4

我想按id按数据分组。id date1 date2 comment1 comment2 grade1 grade2
请帮我破案。提前谢谢。

g2ieeal7

g2ieeal71#

可以对子查询使用以下sql语句:

select q.* ,
       ( select comment from tab where ID = q.ID and date = q.date1 ) as comment1,
       ( select comment from tab where ID = q.ID and date = q.date2 ) as comment2,
       ( select grade from tab where ID = q.ID and date = q.date1 ) as grade1,
       ( select grade from tab where ID = q.ID and date = q.date2 ) as grade2       
  from 
  (
    select ID, min(date) as date1, max(date) as date2  
      from tab
     group by ID
   ) q  

ID  date1       date2       comment1  comment2   grade1  grade2
1   12.07.2013  29.12.2014  asdads    ghjghj        1       2
10  08.10.2015  29.05.2018  cbvcvb    ertert        1       4

rextester演示

相关问题