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

sql seleziona la prima data per più righe

select customer_name,
       kwh,
       reading_date, 
       reading_time
from (
   select customer_name,
          kwh,
          reading_time,
          reading_date,
          row_number() over (partition by customer_name order by reading_time) as rn
   from readings
   where reading_date = date '2012-11-17'
) t
where rn = 1

In alternativa:

select r1.customer_name,
       r1.kwh, 
       r1.reading_date,
       r1.reading_time
from readings r1
where reading_date = date '2012-11-17'
and reading_time = (select min(r2.reading_time)
                    from readings
                    where r2.customer_name = r1.customer_name
                    and r2.read_date = r1.reading_date);

Ma mi aspetto che il primo sia più veloce.

A proposito:perché memorizzi data e ora in due colonne separate? Sei consapevole che questo potrebbe essere gestito meglio con un timestamp colonna?