Search code examples
mysqlsqlgroup-byaggregate-functionsunix-timestamp

Get the average of values in every specific epoch ranges in unix timestamp which returns -1 in specific condition in MySQL


I have a MySQL table which has some records as follows:

unix_timestamp           value

1001                     2
1003                     3
1012                     1
1025                     5
1040                     0
1101                     3
1105                     4
1130                     0
...

I want to compute the average for every 10 epochs to see the following results:

unix_timestamp_range         avg_value

1001-1010                    2.5
1011-1020                    1
1021-1030                    5
1031-1040                    0
1041-1050                   -1
1051-1060                   -1
1061-1070                   -1
1071-1080                   -1
1081-1090                   -1
1091-1100                   -1
1101-1110                    3.5
1111-1120                   -1
1121-1130                    0
...

I saw some similar answers like enter link description here and enter link description here and enter link description here but these answers are not a solution for my specific question. How can I get the above results?


Solution

  • The easiest way to do this is to use a calendar table. Consider this approach:

    SELECT
        CONCAT(CAST(cal.ts AS CHAR(50)), '-', CAST(cal.ts + 9 AS CHAR(50))) AS unix_timestamp_range,
        CASE WHEN COUNT(t.value) > 0 THEN AVG(t.value) ELSE -1 END AS avg_value
    FROM
    (
        SELECT 1001 AS ts UNION ALL
        SELECT 1011 UNION ALL
        SELECT 1021 UNION ALL
        ...
    ) cal
    LEFT JOIN yourTable t
        ON t.unix_timestamp BETWEEN cal.ts AND cal.ts + 9
    GROUP BY
        cal.ts
    ORDER BY
        cal.ts;
    

    In practice, if you have the need to do this sort of query often, instead of the inline subquery labelled as cal above, you might want to have a full dedicated table representing all timestamp ranges.