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

Agregação/pivot SQL postgres de dados por semanas com totais


Aqui você encontra como extrair o número da semana . Em seguida, use um número de semana na instrução CASE

Demonstração do SQLFiddle
WITH T AS
(
SELECT
EventLogs.*
,
extract(week from start_at) - 
extract(week from date_trunc('month', start_at)) + 1 as WeekNo


 FROM EventLogs  
WHERE (start_at BETWEEN '2013-10-01' AND '2013-10-31')
)

SELECT
place_id,
SUM(CASE WHEN WeekNo=1 THEN total_fee_pennies ELSE 0 END) as Week_1,
SUM(CASE WHEN WeekNo=2 THEN total_fee_pennies ELSE 0 END) as Week_2,
SUM(CASE WHEN WeekNo=3 THEN total_fee_pennies ELSE 0 END) as Week_3,
SUM(CASE WHEN WeekNo=4 THEN total_fee_pennies ELSE 0 END) as Week_4,
SUM(CASE WHEN WeekNo=5 THEN total_fee_pennies ELSE 0 END) as Week_5

from T

GROUP BY place_id