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

SQL postgres aggregering/pivot af data efter uger med totaler

Her kan du finde hvordan du udtrækker ugenummeret . Brug derefter et ugenummer i CASE-opgørelsen

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. MariaDB 10 CentOS 7 flytte datadir ve

  2. php POST form forespørgsel opdatering dynamisk variabel

  3. BESTIL EFTER dato med tidligere datoer efter kommende datoer

  4. Lagring af et springsekund i SQL Server 2008