SQL Example: Group Metrics by Week

Overview

This query aggregates key performance metrics on a weekly basis, useful for evaluating weekly trends in spending, traffic, and conversions.

SQL Query

SELECT
  CASE
    WHEN GROUPING(toStartOfWeek (event_date, 1)) = 1 THEN 'Last 6 weeks'
    ELSE CONCAT(
      formatDateTime (MIN(event_date), '%Y-%m-%d'),
      ' to ',
      formatDateTime (MAX(event_date), '%Y-%m-%d')
    )
  END AS week_period,
  SUM(pjt.spend) AS spend,
  SUM(pjt.orders_quantity) AS TW_Convs,
  SUM(pjt.sessions) AS Total_Traffic,
  SUM(pjt.clicks) AS Clicks,
  SUM(pjt.impressions) AS impressions,
  SUM(pjt.order_revenue) AS revenue,
  IFNULL(
    SUM(pjt.order_revenue) / nullIf(SUM(pjt.spend), 0),
    0
  ) AS pixel_roas,
  IFNULL(
    SUM(pjt.spend) / nullIf(SUM(pjt.new_customer_orders), 0),
    0
  ) AS ncpa,
  IFNULL(SUM(pjt.spend) / nullIf(SUM(pjt.clicks), 0), 0) AS cpc,
  IFNULL(
    SUM(pjt.clicks) / nullIf(SUM(pjt.impressions), 0),
    0
  ) AS ctr,
  IFNULL(
    SUM(pjt.website_purchases) / nullIf(SUM(pjt.sessions), 0),
    0
  ) AS pixel_conversion_rate,
  IFNULL(
    SUM(pjt.spend) / nullIf(SUM(pjt.impressions), 0) * 1000,
    0
  ) AS cpm
FROM
  pixel_joined_tvf AS pjt
WHERE
  event_date BETWEEN @start_date AND @end_date
GROUP BY
  GROUPING SETS ((toStartOfWeek (event_date, 1)), ())
HAVING
  COUNT(DISTINCT event_date) >= 7
ORDER BY
  week_period

Tables and Metrics Used

Tables

  • pixel_joined_tvf

Measures

  • spend
  • orders_quantity
  • sessions
  • clicks
  • impressions
  • order_revenue
  • new_customer_orders

Derived Metrics

  • pixel_roas = order_revenue / spend
  • ncpa = spend / new_customer_orders
  • cpc = spend / clicks
  • ctr = clicks / impressions
  • pixel_conversion_rate = website_purchases / sessions
  • cpm = spend / impressions * 1000.

Customization Options

  • Change aggregation to monthly by replacing toStartOfWeek with toStartOfMonth.
  • Filter by channel or campaign by adding additional WHERE clauses.
  • Change the first day of the week
    • toStartOfWeek(event_date, 0) = Sunday as start of week
    • toStartOfWeek(event_date, 1) = Monday as start of week