如何计算两列之间的时间差(最大值)?

时间:2018-02-09 04:59:34

标签: mysql sql

表格如下:

the table look like this

我想计算一天中MAX(盐度)和MAX(深度)之间的时间差异,以及stn_id =' S1'。我该怎么办?

SELECT  `r`.`date` ,  `r`.`time` ,  `r`.`salinity` 
FROM  `samlae` r
INNER JOIN 
(
    SELECT  `date` , MAX(  `salinity` ) AS  `maxsalinity` 
    FROM  `samlae` 
    GROUP BY  `date`
)t ON  `t`.`date` =  `r`.`date` 
AND  `t`.`maxsalinity` =  `r`.`salinity`

1 个答案:

答案 0 :(得分:1)

我会这样做。根据您的确切要求和原始数据集的大小,可能有一种更简单的方法

select max_values.date , (salinity.max_time - depth.max_time) as time_diff
from
    (
        select date, max(salinity) as max_salinity, max(depth) as max_depth
        from table
        group by 1
    ) max_values

inner join
    (
        select date, salinity, max(time) as max_time
        from table
        group by 1,2
    ) salinity
on max_values.date = salinity.date
    and max_values.max_salinity = salinity.salinity

inner join
    (
        select date, depth, max(time) as max_time
        from table
        group by 1,2
    ) depth
on max_values.date = depth.date
    and max_values.max_depth = depth.depth