PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Cara mengoptimalkan kueri SQL dengan fungsi jendela

Saya akan mencoba untuk memindahkan beberapa bagian dari perhitungan ke dalam fase penyisipan baris.

Tambahkan kolom baru:

alter table measurements add consumption real;

Perbarui kolom:

with m1 as (
    select
        id, power_total, created_at,
        lag(power_total) over (partition by device_id order by created_at) prev_power_total,
        lag(created_at) over (partition by device_id order by created_at) prev_created_at
    from measurements
    )
update measurements m2
set consumption = 
    (m1.power_total+ m1.prev_power_total)*
    extract(epoch from m1.created_at- m1.prev_created_at)
from m1
where m2.id = m1.id;

Buat pemicu:

create or replace function before_insert_on_measurements()
returns trigger language plpgsql
as $$
declare
    rec record;
begin
    select power_total, created_at into rec
    from measurements
    where device_id = new.device_id
    order by created_at desc
    limit 1;
    new.consumption:= 
        (new.power_total+ rec.power_total)*
        extract(epoch from new.created_at- rec.created_at);
    return new;
end $$;

create trigger before_insert_on_measurements
before insert on measurements
for each row execute procedure before_insert_on_measurements();

Pertanyaannya:

select device_id, sum(consumption) total_consumption
from measurements
-- where conditions
group by 1
order by 1


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana LocalTimeStamp() Bekerja di PostgreSQL

  2. Bagaimana current_date Bekerja di PostgreSQL

  3. pqxx::result::tuple belum dideklarasikan (perpustakaan PostgreSQL untuk c++)

  4. Bagaimana cara menanyakan array jsonb dengan operator IN

  5. agregat json postgresql