PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Query per selezionare più dati insieme a valori medi in un momento specifico utilizzando Postgres

Puoi convertire avg_aa bigint o double precision. Prima sottrai ID e nome dal campo del nome, quindi calcola la media per 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;

Si prega di controllare dall'URL https://dbfiddle.uk/?rdbms=postgres_11&fiddle=8113ce4fd19d2865dcc9757d

Usa la doppia precisione nella colonna media

-- 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;

Verificare dall'URL https://dbfiddle.uk/?rdbms=postgres_11&fiddle=c70fe828008b13f7eb3feefc080a>8