仅获取列中的最大值和最小值-SQL

时间:2018-10-04 07:04:21

标签: mysql sql

这里我提到一个数据,我只想将最大和最小日期值作为新行读取到我的新表中。

   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

请帮助我解决此问题。 预先感谢。

1 个答案:

答案 0 :(得分:2)

您可以在子查询中使用以下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 Demo