PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Consulta para selecionar vários dados junto com valores médios entre um horário específico usando o Postgres


Você pode converter avg_aa bigint ou double precision. Primeiro, subtraia o id e o nome do campo de nome e, em seguida, calcule a média por id e data.
-- PostgreSQL(v11)
    WITH cte_t AS (
     SELECT LEFT(name, 1) id
          , RIGHT(name, POSITION('.' IN REVERSE(name)) - 1) t_name
          , value
          , time_stamp
     FROM test
)
SELECT id
          , time_stamp :: DATE "date"
          , AVG(CASE WHEN t_name = 'aa' THEN value END) :: BIGINT "avg(aa)"
          , AVG(CASE WHEN t_name = 'bb' THEN value END) :: BIGINT "avg(bb)"
          , AVG(CASE WHEN t_name = 'cc' THEN value END) :: BIGINT "avg(cc)"
     FROM cte_t
     GROUP BY id, time_stamp :: DATE
     ORDER BY "date", id;

Verifique no URL https://dbfiddle.uk/?rdbms=postgres_11&fiddle=8113ce4fd759
Use precisão dupla na coluna avg
-- PostgreSQL(v11)
WITH cte_t AS (
     SELECT LEFT(name, 1) id
          , RIGHT(name, POSITION('.' IN REVERSE(name)) - 1) t_name
          , value
          , time_stamp
     FROM test
)
SELECT id
          , time_stamp :: DATE "date"
          , AVG(CASE WHEN t_name = 'aa' THEN value END) :: DOUBLE PRECISION "avg(aa)"
          , AVG(CASE WHEN t_name = 'bb' THEN value END) :: DOUBLE PRECISION "avg(bb)"
          , AVG(CASE WHEN t_name = 'cc' THEN value END) :: DOUBLE PRECISION "avg(cc)"
     FROM cte_t
     GROUP BY id, time_stamp :: DATE
     ORDER BY "date", id;

Verifique no URL
https://dbfiddle.uk/?rdbms=postgres_11&fiddle=c70fe828008b13f7eb3feefc>