D
D
des1roer2015-05-14 09:58:23
PostgreSQL
des1roer, 2015-05-14 09:58:23

Postgres sum over different intervals?

Is it possible to implement the following - in one request to receive the amount for both the current day and the current month?

select
  sum(value::real) as sum
FROM 
  analiz_data 
--and CURRENT_DATE =f_timestamp::date
--and to_char(current_timestamp, 'YYYY-MM') = to_char(f_timestamp, 'YYYY-MM')

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Melkij, 2015-05-14
@des1roer

A bit of computational load:

select
sum(value) as month_sum,
sum(case when CURRENT_DATE =f_timestamp::date then value else 0 end) as today_sum
from ... where за этот месяц

A
Andrey Mokhov, 2015-05-14
@mokhovcom

you can, use over
UPD , corrected the request, it's more correct

SELECT
    d.*,
    sum(d.day_sum) OVER (PARTITION BY date_trunc('month', d.f_timestamp)) as month_sum
FROM (
        SELECT
            f_timestamp::date,
            sum(value::real) as day_sum
        FROM analiz_data
        GROUP BY f_timestamp::date
    ) d

D
des1roer, 2015-05-14
@des1roer

select
sum(value::REAL) as month_sum,
sum(case when CURRENT_DATE =f_timestamp::date then value::REAL else 0 end) as today_sum
from analiz_data where to_char(current_timestamp, 'YYYY-MM') = to_char(f_timestamp, 'YYYY-MM')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question