如何在SQL出现最小值或最大值时获取时间戳?

时间:2016-12-28 15:24:38

标签: sql sqlite greatest-n-per-group

我有一个包含timestamp列和value列的数据库。记录定期进行。现在我想做每日聚合。这样做了:

SELECT
    strftime("%Y-%m-%d", timestamp) AS "new_timestamp",
    AVG(value) as value_avg,
    MIN(value) as value_min,
    MAX(value) as value_max,
    COUNT(*) as num_samples,
    /* ... something for when max and min value occurs */
FROM my_table
GROUP BY "new_timestamp"

:当当天发生MIN或MAX时,如何获得时间戳/时间

编辑:在我的具体情况下,如果有多个最小值或最大值,则应选择哪一个并不重要。我正在使用SQLite。

1 个答案:

答案 0 :(得分:0)

使用strftime()表明您使用的是SQLite。如果是这样,那么相关子查询可能是进行计算的最简单方法。

我认为以下内容可行:

SELECT strftime('%Y-%m-%d', timestamp) AS "new_timestamp",
       AVG(value) as value_avg,
       MIN(value) as value_min,
       MAX(value) as value_max,
       COUNT(*) as num_samples,
       (SELECT t2.timestamp
        FROM my_table t2
        WHERE strftime('%Y-%m-%d', t2.timestamp) = strftime('%Y-%m-%d', t.timestamp)
        ORDER BY value desc
       ) as timestamp_max,
       (SELECT t2.timestamp
        FROM my_table t2
        WHERE strftime('%Y-%m-%d', t2.timestamp) = strftime('%Y-%m-%d', t.timestamp)
        ORDER BY value asc
       ) as timestamp_min
FROM my_table t
GROUP BY "new_timestamp"