RaccoonLaptopGif

sql hacks

Here is a list of some useful SQL hacks that I use almost every day to make my work a little bit easier:

Here’s a code that covers what I described in the bullet points bk who wants to read text if you can just read code, hehe

WITH
-- in this query we are pulling sales data for the past 90 days
-- on weekly level and seller account segment
-- for very important stakeholder ofc and for important reason

calendar AS (
  SELECT
    *,
    date_day AS amsterdamEventDate
  FROM 'bq_project.subfolder.dim_financial_calendar'
  WHERE
    date_day BETWEEN CURRENT_DATE()-90 AND CURRENT_DATE()
  ),

accounts AS (
  SELECT
    *
  FROM 'bq_project.subfolder.dim_account_list'
  ),

sales AS (
  SELECT
    *
  FROM 'bq_project.subfolder.fct_sales'
  WHERE
    -- only last 90 days are relevant to request
    amsterdamEventDate BETWEEN CURRENT_DATE()-90 AND CURRENT_DATE()
  ),

-- in this CTE we are joining all tables
-- and aggregating on segment and week level
sales_aggregations AS (
  SELECT
    calendar.date_week AS amsterdamEventWeek,
    accounts.segment,
    SUM(sales.orderTotal) AS salesSegment,
    SUM(sales.orderTotal)
      OVER (PARTITION BY calendar.date_week) AS salesAllSegments
  FROM calendar
  LEFT JOIN sales USING (amsterdamEventDate)
  LEFT JOIN accounts USING (accountId)
  GROUP BY ALL, calendar.date_week

)

SELECT
  *,
  ROUND(
    SAFE_DIVIDE(salesSegment, salesAllSegments)
    ,2) AS proportionSegment
FROM sales_aggregations
WHERE 1=1
--AND segment = "Longtail"
ORDER BY amsterdamEventWeek

Image source: one of the first 5 images on google search