如何获得每个值的1条记录

时间:2017-05-23 07:36:31

标签: mysql sql mariadb

我需要记录每个TypV,其中ExpTime大于2017-05-24

示例数据:

PHVal TypV  WTemp   ExpTime
----------------------------------
 3.00   A   22.00   2017-03-29 02:34:00
 6.00   A   45.00   2017-06-29 02:34:00
 8.22   A   12.00   2017-08-25 01:25:00
 3.00   A   22.00   2017-03-29 02:34:00
11.00   B   11.00   2016-06-29 02:34:00
 1.22   C   12.00   2017-04-25 11:25:00
17.00   B    1.70   2017-05-30 02:44:00
27.22   C   76.00   2017-07-25 08:21:00
11.00   B   18.30   2017-09-29 14:34:00
27.22   C   32.00   2017-11-12 11:31:00

如果我运行SQL查询

SELECT 
 PHVal, TypV,   WTemp,  ExpTime
FROM tempsurvey
WHERE 
 ExpTime > to_date('2017-05-24')

我得到了每个TypV的几条记录,但我希望输出:

PHVal TypV  WTemp   ExpTime
----------------------------------
 6.00   A   45.00   2017-06-29 02:34:00
17.00   B    1.70   2017-05-30 02:44:00
27.22   C   76.00   2017-07-25 08:21:00

1 个答案:

答案 0 :(得分:1)

我希望您想要拥有ExpTime > '2017-05-24'的行,并选择一个具有每个TypV的最小日期的行。

<强>查询

select t2.PHVal,
t2.TypV,
t2.WTemp,
t2.ExpTime
from
(
   select PHVal,
   TypV,
   WTemp,
   ExpTime,
   ( 
      case TypV 
      when @curA
      then @curR := @curR + 1 
      else @curR := 1 and @curA := TypV end
   ) + 1 as rn
  from (
      select * from `your_table_name` 
      where cast(ExpTime as date) > '2017-05-24'
 ) t,
 (select @curR := 0, @curA := '') r
 order by TypV, ExpTime
)t2
where t2.rn = 1
order by TypV;

<强> Find demo here

相关问题