sql >> Databasteknik >  >> RDS >> PostgreSQL

SQL postgres aggregering/pivotering av data efter veckor med totaler

Här kan du hitta hur du extraherar veckonumret . Använd sedan ett veckonummer i CASE-uttrycket

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. Hur UTC_TIMESTAMP() fungerar i MariaDB

  2. Konvertera hex till binär i MySQL

  3. Paket ur funktion fel vid anrop av MySQL lagrad proc

  4. SQL-fråga med ON DUPLICATE KEY UPDATE förtydligande behövs