PostgreSQL
 sql >> Base de données >  >> RDS >> PostgreSQL

Agrégation/pivot SQL postgres des données par semaines avec totaux

Ici vous pouvez trouver comment extraire le numéro de semaine . Utilisez ensuite un numéro de semaine dans l'instruction CASE

Démo 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