sql >> Database >  >> RDS >> PostgreSQL

SQL postgres-aggregatie/pivot van gegevens per week met totalen

Hier vindt u hoe u het weeknummer kunt extraheren . Gebruik dan een weeknummer in het CASE-statement

SQLFiddle-demo

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



  1. Ontsmet/ontsnap ik op de juiste manier?

  2. Hoe maak je twee select-statements als twee kolommen in postgres

  3. Het standaard gebruikerswachtwoord instellen in PostgreSQL

  4. Wat te controleren in MySQL 8.0