nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: world_bank (snowflake)
Question: Which region has the highest median GDP (constant 2015 US$) value?
SQL:
WITH country_data AS (
  -- CTE for country descriptive data
  SELECT 
    country_code, 
    short_name AS country,
    region, 
    income_group 
  FROM 
    `bigquery-public-data.world_bank_wdi.country_summary`
),

gdp_data AS (
  -- Filter data to only include GDP values
  SELECT 
    data.country_code, 
    country,
    region,
    value AS gdp_value
  FROM 
    `bigquery-public-data.world_bank_wdi.indicators_data` data
  LEFT JOIN country_data
    ON data.country_code = country_data.country_code
  WHERE indicator_code = "NY.GDP.MKTP.KD" -- GDP Indicator
    AND country_data.region IS NOT NULL
    AND country_data.income_group IS NOT NULL
),

cal_median_gdp AS (
  -- Calculate the median GDP value for each region
  SELECT 
    region,
    APPROX_QUANTILES(gdp_value, 2)[OFFSET(1)] AS median_gdp
  FROM gdp_data
  GROUP BY region
)
-- Select the regions with their median GDP values
SELECT 
  region
FROM 
  cal_median_gdp
ORDER BY median_gdp DESC
LIMIT 1;
Database: META_KAGGLE (snowflake)
Question: Using the data from Forum Message Votes and Users tables, find the top three users who have received the most distinct upvotes on the Kaggle forum. For each of these users, list their username, the total number of distinct upvotes they have received (based on the ToUserId field), and the total number of distinct upvotes they have given (based on the FromUserId field), sorted by the number of upvotes received in descending order and restricted to only the top three results.
SQL:
Database: hacker_news (snowflake)
Question: I want to identify users who had activity followed by inactivity. Specifically, find the user ID and their corresponding month number (counting from their first activity month) for the user with the highest month number who became inactive (no activity recorded) after their last recorded activity month. For this analysis, only consider data up until September 10, 2024, and ensure the month number represents the count of months since the user's first activity. The user should have at least one month where they were expected to be active (within their activity span) but actually had no records.
SQL:
Database: irs_990 (snowflake)
Question: Which three years in 2012-2017 have the smallest absolute difference between median revenue and median functional expenses for organizations filing IRS 990 forms? Please output three years and respective differences.
SQL:
WITH RankedData AS (
    SELECT
        CONCAT("20", _TABLE_SUFFIX) AS year_filed,
        totrevenue,
        totfuncexpns,
        ROW_NUMBER() OVER (PARTITION BY CONCAT("20", _TABLE_SUFFIX) ORDER BY totrevenue) 
        AS revenue_rank,
        ROW_NUMBER() OVER (PARTITION BY CONCAT("20", _TABLE_SUFFIX) ORDER BY totfuncexpns) 
        AS expense_rank,
        COUNT(*) OVER (PARTITION BY CONCAT("20", _TABLE_SUFFIX)) AS total_count
    FROM 
        `bigquery-public-data.irs_990.irs_990_20*`
),

YearlyMedians AS (
    SELECT
        year_filed,
        IF(MOD(total_count, 2) = 1, 
           MAX(CASE WHEN revenue_rank = (total_count + 1) / 2 THEN totrevenue END),
           AVG(CASE WHEN revenue_rank IN ((total_count / 2), (total_count / 2) + 1) THEN totrevenue END)
        ) AS median_revenue,
        IF(MOD(total_count, 2) = 1, 
           MAX(CASE WHEN expense_rank = (total_count + 1) / 2 THEN totfuncexpns END),
           AVG(CASE WHEN expense_rank IN ((total_count / 2), (total_count / 2) + 1) THEN totfuncexpns END)
        ) AS median_expense
    FROM
        RankedData
    GROUP BY
        year_filed, total_count
),

DifferenceCalculations AS (
    SELECT
        year_filed,
        median_revenue,
        median_expense,
        ABS(median_revenue - median_expense) AS difference
    FROM
        YearlyMedians
)

SELECT
    year_filed,
    difference
FROM
    DifferenceCalculations
WHERE
    year_filed BETWEEN '2012' AND '2017'
ORDER BY
    difference ASC
LIMIT 3;
Database: ecommerce (snowflake)
Question: After removing any duplicate records from the rev_transactions dataset, identify each channel grouping that has transactions from more than one country. For each such channel grouping, find the country with the highest total number of transactions and report both the country name and the sum of transactions for that channel grouping.
SQL:
WITH tmp AS (
  SELECT DISTINCT *
  FROM `data-to-insights.ecommerce.rev_transactions`
  -- Removing duplicated values
),
tmp1 AS (
  SELECT 
    tmp.channelGrouping,
    tmp.geoNetwork_country,
    SUM(tmp.totals_transactions) AS tt
  FROM tmp
  GROUP BY 1, 2
),
tmp2 AS (
  SELECT 
    channelGrouping,
    geoNetwork_country,
    SUM(tt) AS TotalTransaction,
    COUNT(DISTINCT geoNetwork_country) OVER (PARTITION BY channelGrouping) AS CountryCount
  FROM tmp1
  GROUP BY channelGrouping, geoNetwork_country
),
tmp3 AS (
  SELECT
    channelGrouping,
    geoNetwork_country AS Country,
    TotalTransaction,
    RANK() OVER (PARTITION BY channelGrouping ORDER BY TotalTransaction DESC) AS rnk
  FROM tmp2
  WHERE CountryCount > 1
)
SELECT
  channelGrouping,
  Country,
  TotalTransaction
FROM tmp3
WHERE rnk = 1;
Database: ecommerce (snowflake)
Question: Calculate the conversion rate from unique visitors to purchasers by using data exclusively from the `web_analytics` table in the `data-to-insights.ecommerce` dataset. A visitor is defined as a unique `fullVisitorId` present in the table, while a purchaser is a visitor who has at least one transaction recorded (`totals.transactions` is not null). The conversion rate is computed by dividing the number of unique purchasers by the total number of unique visitors. Additionally, calculate the average number of transactions per purchaser, considering only those visitors who have made at least one transaction.
SQL:
WITH visitors AS (
  SELECT
    COUNT(DISTINCT fullVisitorId) AS total_visitors
  FROM 
    `data-to-insights.ecommerce.web_analytics`
),

purchasers AS (
  SELECT
    COUNT(DISTINCT fullVisitorId) AS total_purchasers
  FROM 
    `data-to-insights.ecommerce.web_analytics`
  WHERE 
    totals.transactions IS NOT NULL
),

transactions AS (
  SELECT
    COUNT(*) AS total_transactions,
    AVG(totals.transactions) AS avg_transactions_per_purchaser
  FROM 
    `data-to-insights.ecommerce.web_analytics`
  WHERE 
    totals.transactions IS NOT NULL
)

SELECT
  p.total_purchasers / v.total_visitors AS conversion_rate,
  a.avg_transactions_per_purchaser AS avg_transactions_per_purchaser
FROM
  visitors v,
  purchasers p,
  transactions a;
Database: META_KAGGLE (snowflake)
Question: Please provide the creation date, title, parent forum title, reply count, distinct user replies count, total upvotes, and total views for the earliest five forum topics that belong to any sub-forum under the parent forum titled "General". The reply count should be calculated as the total number of messages associated with each topic, and the distinct user replies count should be the number of unique users who have posted messages in the topic. The upvotes should be calculated as the total number of upvotes on all messages within each topic. If any values are missing or None, please treat them as zero
SQL:
Database: META_KAGGLE (snowflake)
Question: Identify the pair of Kaggle users involved in ForumMessageVotes such that one user has given the other the greatest distinct number of upvotes, then also display how many upvotes that recipient returned. Present the usernames of both users, the total distinct upvotes one received from the other, and the upvotes they gave back, sorting by the highest received count and then by the highest given count, and show only the top result.
SQL:
WITH UserPairUpvotes AS (
  SELECT
    ToUsers."UserName" AS "ToUserName",
    FromUsers."UserName" AS "FromUserName",
    COUNT(DISTINCT "ForumMessageVotes"."Id") AS "UpvoteCount"
  FROM META_KAGGLE.META_KAGGLE.FORUMMESSAGEVOTES AS "ForumMessageVotes"
  INNER JOIN META_KAGGLE.META_KAGGLE.USERS AS FromUsers
    ON FromUsers."Id" = "ForumMessageVotes"."FromUserId"
  INNER JOIN META_KAGGLE.META_KAGGLE.USERS AS ToUsers
    ON ToUsers."Id" = "ForumMessageVotes"."ToUserId"
  GROUP BY
    ToUsers."UserName",
    FromUsers."UserName"
),
TopPairs AS (
  SELECT
    "ToUserName",
    "FromUserName",
    "UpvoteCount",
    ROW_NUMBER() OVER (ORDER BY "UpvoteCount" DESC) AS "Rank"
  FROM UserPairUpvotes
),
ReciprocalUpvotes AS (
  SELECT
    t."ToUserName",
    t."FromUserName",
    t."UpvoteCount" AS "UpvotesReceived",
    COALESCE(u."UpvoteCount", 0) AS "UpvotesGiven"
  FROM TopPairs t
  LEFT JOIN UserPairUpvotes u
    ON t."ToUserName" = u."FromUserName" AND t."FromUserName" = u."ToUserName"
  WHERE t."Rank" = 1
)
SELECT
  "ToUserName" AS "UpvotedUserName",
  "FromUserName" AS "UpvotingUserName",
  "UpvotesReceived" AS "UpvotesReceivedByUpvotedUser",
  "UpvotesGiven" AS "UpvotesGivenByUpvotedUser"
FROM ReciprocalUpvotes
ORDER BY "UpvotesReceived" DESC, "UpvotesGiven" DESC;
Database: DEATH (snowflake)
Question: Please provide, for each age from 12 through 18 (inclusive), the total number of deaths and the number of deaths among individuals identified as Black (based on race descriptions containing the word ‘black’), specifically for deaths associated with ICD-10 codes whose descriptions include the word ‘vehicle’ and for deaths associated with ICD-10 codes whose descriptions include the word ‘firearm.’ Use the EntityAxisConditions table to determine which ICD-10 codes were involved in each death, rather than joining ICD-10 code information directly on the death records.
SQL:
WITH BlackRace AS (
    SELECT CAST("Code" AS INT) AS CODE
    FROM DEATH.DEATH.RACE
    WHERE LOWER("Description") LIKE '%black%'
)
SELECT 
    v."Age", 
    v."Total" AS "Vehicle_Total", 
    v."Black" AS "Vehicle_Black",
    g."Total" AS "Gun_Total", 
    g."Black" AS "Gun_Black"
FROM (
    SELECT 
        "Age", 
        COUNT(*) AS "Total", 
        COUNT_IF("Race" IN (SELECT CODE FROM BlackRace)) AS "Black"
    FROM DEATH.DEATH.DEATHRECORDS d
    JOIN (
        SELECT 
            DISTINCT e."DeathRecordId" AS "id"
        FROM DEATH.DEATH.ENTITYAXISCONDITIONS e
        JOIN (
            SELECT * 
            FROM DEATH.DEATH.ICD10CODE 
            WHERE LOWER("Description") LIKE '%vehicle%'
        ) c 
        ON e."Icd10Code" = c."Code"
    ) f
    ON d."Id" = f."id"
    WHERE "Age" BETWEEN 12 AND 18
    GROUP BY "Age"
) v  -- Vehicle

JOIN (
    SELECT 
        "Age", 
        COUNT(*) AS "Total", 
        COUNT_IF("Race" IN (SELECT CODE FROM BlackRace)) AS "Black"
    FROM DEATH.DEATH.DEATHRECORDS d
    JOIN (
        SELECT 
            DISTINCT e."DeathRecordId" AS "id"
        FROM DEATH.DEATH.ENTITYAXISCONDITIONS e
        JOIN (
            SELECT 
                "Code", "Description" 
            FROM DEATH.DEATH.ICD10CODE
            WHERE "Description" LIKE '%firearm%'
        ) c 
        ON e."Icd10Code" = c."Code"
    ) f
    ON d."Id" = f."id"
    WHERE "Age" BETWEEN 12 AND 18
    GROUP BY "Age"
) g
ON g."Age" = v."Age";
Database: ga4 (snowflake)
Question: I want to know the preferences of customers who purchased the Google Navy Speckled Tee in December 2020. What other product was purchased with the highest total quantity alongside this item?
SQL:
WITH
  Params AS (
    SELECT 'Google Navy Speckled Tee' AS selected_product
  ),
  PurchaseEvents AS (
    SELECT
      user_pseudo_id,
      items
    FROM
      `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
    WHERE
      _TABLE_SUFFIX BETWEEN '20201201' AND '20201231'
      AND event_name = 'purchase'
  ),
  ProductABuyers AS (
    SELECT DISTINCT
      user_pseudo_id
    FROM
      Params,
      PurchaseEvents,
      UNNEST(items) AS items
    WHERE
      items.item_name = selected_product
  )
SELECT
  items.item_name AS item_name,
  SUM(items.quantity) AS item_quantity
FROM
  Params,
  PurchaseEvents,
  UNNEST(items) AS items
WHERE
  user_pseudo_id IN (SELECT user_pseudo_id FROM ProductABuyers)
  AND items.item_name != selected_product
GROUP BY 1
ORDER BY item_quantity DESC
LIMIT 1;
Database: ga4 (snowflake)
Question: Tell me the most purchased other products and their quantities by customers who bought the Google Red Speckled Tee each month for the three months starting from November 2020.
SQL:
WITH
Params AS (
  SELECT 'Google Red Speckled Tee' AS selected_product
),
DateRanges AS (
  SELECT '20201101' AS start_date, '20201130' AS end_date, '202011' AS period UNION ALL
  SELECT '20201201', '20201231', '202012' UNION ALL
  SELECT '20210101', '20210131', '202101'
),
PurchaseEvents AS (
  SELECT
    period,
    user_pseudo_id,
    items
  FROM
    DateRanges
  JOIN
    `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
    ON _TABLE_SUFFIX BETWEEN start_date AND end_date
  WHERE
    event_name = 'purchase'
),
ProductABuyers AS (
  SELECT DISTINCT
    period,
    user_pseudo_id
  FROM
    Params,
    PurchaseEvents,
    UNNEST(items) AS items
  WHERE
    items.item_name = selected_product
),
TopProducts AS (
  SELECT
    pe.period,
    items.item_name AS item_name,
    SUM(items.quantity) AS item_quantity
  FROM
    Params,
    PurchaseEvents pe,
    UNNEST(items) AS items
  WHERE
    user_pseudo_id IN (SELECT user_pseudo_id FROM ProductABuyers pb WHERE pb.period = pe.period)
    AND items.item_name != selected_product
  GROUP BY
    pe.period, items.item_name
),
TopProductPerPeriod AS (
  SELECT
    period,
    item_name,
    item_quantity
  FROM (
    SELECT
      period,
      item_name,
      item_quantity,
      RANK() OVER (PARTITION BY period ORDER BY item_quantity DESC) AS rank
    FROM
      TopProducts
  )
  WHERE
    rank = 1
)
SELECT
  period,
  item_name,
  item_quantity
FROM
  TopProductPerPeriod
ORDER BY
  period;
Database: firebase (snowflake)
Question: I'm trying to evaluate which board types were most effective on September 15, 2018. Can you find out the average scores for each board type from the quick play mode completions on that day?
SQL:
WITH EventData AS (
    SELECT 
        user_pseudo_id, 
        event_timestamp, 
        param
    FROM 
        `firebase-public-project.analytics_153293282.events_20180915`,
        UNNEST(event_params) AS param
    WHERE 
        event_name = "level_complete_quickplay"
        AND (param.key = "value" OR param.key = "board")
),
ProcessedData AS (
    SELECT 
        user_pseudo_id, 
        event_timestamp, 
        MAX(IF(param.key = "value", param.value.int_value, NULL)) AS score,
        MAX(IF(param.key = "board", param.value.string_value, NULL)) AS board_type
    FROM 
        EventData
    GROUP BY 
        user_pseudo_id, 
        event_timestamp
)
SELECT 
    ANY_VALUE(board_type) AS board, 
    AVG(score) AS average_score
FROM 
    ProcessedData
GROUP BY 
    board_type
Database: ga4 (snowflake)
Question: Can you figure out the average difference in pageviews between users who bought something and those who didn’t in December 2020? Just label anyone who was involved in purchase events as a purchaser.
SQL:
WITH
  UserInfo AS (
    SELECT
      user_pseudo_id,
      COUNTIF(event_name = 'page_view') AS page_view_count,
      COUNTIF(event_name IN ('in_app_purchase', 'purchase')) AS purchase_event_count
    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
    WHERE _TABLE_SUFFIX BETWEEN '20201201' AND '20201231'
    GROUP BY 1
  ),
  Averages AS (
    SELECT
      (purchase_event_count > 0) AS purchaser,
      COUNT(*) AS user_count,
      SUM(page_view_count) AS total_page_views,
      SUM(page_view_count) / COUNT(*) AS avg_page_views
    FROM UserInfo
    GROUP BY 1
  )

SELECT
  MAX(CASE WHEN purchaser THEN avg_page_views ELSE 0 END) -
  MAX(CASE WHEN NOT purchaser THEN avg_page_views ELSE 0 END) AS avg_page_views_difference
FROM Averages;
Database: ga4 (snowflake)
Question: Could you provide the total number of page views for each day in November 2020 as well as the average number of page views per user on those days, restricted to users who made at least one purchase in November 2020?
SQL:
WITH
  UserInfo AS (
    SELECT
      user_pseudo_id,
      PARSE_DATE('%Y%m%d', event_date) AS event_date,
      COUNTIF(event_name = 'page_view') AS page_view_count,
      COUNTIF(event_name = 'purchase') AS purchase_event_count
    FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
    WHERE _TABLE_SUFFIX BETWEEN '20201101' AND '20201130'
    GROUP BY 1, 2
  )
SELECT
  event_date,
  SUM(page_view_count) / COUNT(*) AS avg_page_views,
  SUM(page_view_count)
FROM UserInfo
WHERE purchase_event_count > 0
GROUP BY event_date
ORDER BY event_date;
Database: ga4 (snowflake)
Question: How many distinct users viewed the most frequently visited page during January 2021?
SQL:
WITH unnested_events AS (
  SELECT
    MAX(CASE WHEN event_params.key = 'page_location' THEN event_params.value.string_value END) AS page_location,
    user_pseudo_id,
    event_timestamp
  FROM
    `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`,
    UNNEST(event_params) AS event_params
  WHERE
    _TABLE_SUFFIX BETWEEN '20210101' AND '20210131'
    AND event_name = 'page_view'
  GROUP BY user_pseudo_id,event_timestamp
),
temp AS (
    SELECT
    page_location,
    COUNT(*) AS event_count,
    COUNT(DISTINCT user_pseudo_id) AS users
    FROM
    unnested_events
    GROUP BY page_location
    ORDER BY event_count DESC
)

SELECT users 
FROM
temp
LIMIT 1
Database: ga4 (snowflake)
Question: Can you generate the navigation flow for user with pseudo_id '1362228.4966015575' on January 28th 2021, showing only the page_view events? Please connect the page titles with '>>' between each step, convert product detail pages to 'PDP' and product listing pages to 'PLP' based on the URL structure, and merge adjacent identical pages so they only appear once in the sequence. I need to understand how this specific user navigated through our website on that day.
SQL:
Database: ga4 (snowflake)
Question: On November 30, 2020, identify the item category with the highest tax rate by dividing tax value in usd by purchase revenue in usd for purchase events, and then retrieve the transaction IDs, total item quantities, and both purchase revenue in usd and purchase revenue for those purchase events in that top-tax-rate category.
SQL:
WITH top_category AS (
  SELECT
    product.item_category,
    SUM(ecommerce.tax_value_in_usd) / SUM(ecommerce.purchase_revenue_in_usd) AS tax_rate
  FROM
    bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20201130,
    UNNEST(items) AS product
  WHERE
    event_name = 'purchase'
  GROUP BY
    product.item_category
  ORDER BY
    tax_rate DESC
  LIMIT 1
)

SELECT
    ecommerce.transaction_id,
    SUM(ecommerce.total_item_quantity) AS total_item_quantity,
    SUM(ecommerce.purchase_revenue_in_usd) AS purchase_revenue_in_usd,
    SUM(ecommerce.purchase_revenue) AS purchase_revenue
FROM
    bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20201130, 
    UNNEST(items) AS product
JOIN top_category
ON product.item_category = top_category.item_category
WHERE
    event_name = 'purchase'
GROUP BY
    ecommerce.transaction_id;
Database: firebase (snowflake)
Question: Could you determine what percentage of users either did not uninstall our app within seven days or never uninstalled it after installing during August and September 2018?
SQL:
WITH
--List of users who installed
sept_cohort AS (
  SELECT DISTINCT user_pseudo_id,
  FORMAT_DATE('%Y-%m-%d', PARSE_DATE('%Y%m%d', event_date)) AS date_first_open,
  FROM `firebase-public-project.analytics_153293282.events_*`
  WHERE event_name = 'first_open'
  AND _TABLE_SUFFIX BETWEEN '20180801' and '20180930'
),
--Get the list of users who uninstalled
uninstallers AS (
  SELECT DISTINCT user_pseudo_id,
  FORMAT_DATE('%Y-%m-%d', PARSE_DATE('%Y%m%d', event_date)) AS date_app_remove,
  FROM `firebase-public-project.analytics_153293282.events_*`
  WHERE event_name = 'app_remove'
  AND _TABLE_SUFFIX BETWEEN '20180801' and '20180930'
),
--Join the 2 tables and compute for # of days to uninstall
joined AS (
  SELECT a.*,
  b.date_app_remove,
  DATE_DIFF(DATE(b.date_app_remove), DATE(a.date_first_open), DAY) AS days_to_uninstall
  FROM sept_cohort a
  LEFT JOIN uninstallers b
  ON a.user_pseudo_id = b.user_pseudo_id
)
--Compute for the percentage
SELECT
COUNT(DISTINCT
CASE WHEN days_to_uninstall > 7 OR days_to_uninstall IS NULL THEN user_pseudo_id END) /
COUNT(DISTINCT user_pseudo_id)
AS percent_users_7_days
FROM joined
Database: firebase (snowflake)
Question: Can you group users by the week of their first session start, starting from July 2, 2018? For each group, calculate the retention rate in the fourth week (i.e., the percentage of users from the original group who returned in the fourth week after their first session). Please identify the cohort with the highest retention rate in the fourth week, and name the group by the Monday date of the cohort's first session week. Return the result in the format "YYYY-MM-DD".
SQL:
Database: firebase (snowflake)
Question: Conduct a weekly cohort analysis for user retention, starting from July 9, 2018, and ending on October 2, 2018. Group users by the week of their first session_start event (with weeks starting on Monday), and identify new users as those where the event_date matches the date of their user_first_touch_timestamp. Calculate the Week 2 retention rate for each weekly cohort, defined as the percentage of users who had a session_start event exactly 2 weeks after their first week. Only include cohorts from July 9, 2018 through September 17, 2018 (the last cohort that can be analyzed for 2-week retention given the available data). Present the results with each weekly cohort and its corresponding Week 2 retention rate, ordered by cohort date.
SQL:
Database: firebase (snowflake)
Question: Please perform a 7-day retention analysis for users who first session start the app during the week starting on July 2, 2018. For each week from Week 0 (the week of their first session) to Week 4, provide the total number of new users in Week 0 and the number of retained users for each subsequent week. Ensuring that you only count events up to October 2, 2018, and group dates by Monday-based weeks
SQL:
WITH dates AS (
    SELECT 
        DATE('2018-07-02') AS start_date,
        DATE('2018-10-02') AS end_date,
        DATE_ADD(DATE_TRUNC(DATE('2018-10-02'), WEEK(TUESDAY)), INTERVAL -4 WEEK) AS min_date
),

date_table AS (
    SELECT DISTINCT 
        PARSE_DATE('%Y%m%d', `event_date`) AS event_date,
        user_pseudo_id,
        CASE 
            WHEN DATE_DIFF(PARSE_DATE('%Y%m%d', `event_date`), DATE(TIMESTAMP_MICROS(user_first_touch_timestamp)), DAY) = 0 
            THEN 1 
            ELSE 0 
        END AS is_new_user
    FROM 
        `firebase-public-project.analytics_153293282.events_*` 
    WHERE 
        event_name = 'session_start'
),

new_user_list AS (
    SELECT DISTINCT 
        user_pseudo_id,
        event_date
    FROM 
        date_table
    WHERE 
        is_new_user = 1
),

days_since_start_table AS (
    SELECT DISTINCT 
        is_new_user,
        nu.event_date AS date_cohort,
        dt.user_pseudo_id,
        dt.event_date,
        DATE_DIFF(dt.event_date, nu.event_date, DAY) AS days_since_start
    FROM 
        date_table dt
    JOIN 
        new_user_list nu ON dt.user_pseudo_id = nu.user_pseudo_id
),

weeks_retention AS (
    SELECT 
        date_cohort,
        DATE_TRUNC(date_cohort, WEEK(MONDAY)) AS week_cohort,
        user_pseudo_id,
        days_since_start,
        CASE 
            WHEN days_since_start = 0 
            THEN 0 
            ELSE CEIL(days_since_start / 7) 
        END AS weeks_since_start
    FROM 
        days_since_start_table
),
RETENTION_INFO AS (
  SELECT 
      week_cohort,
      weeks_since_start,
      COUNT(DISTINCT user_pseudo_id) AS retained_users
  FROM 
      weeks_retention
  WHERE 
      week_cohort <= (SELECT min_date FROM dates)
  GROUP BY 
      week_cohort,
      weeks_since_start
  HAVING 
      weeks_since_start <= 4
  ORDER BY 
      week_cohort,
      weeks_since_start
)

SELECT weeks_since_start, retained_users
FROM RETENTION_INFO
WHERE week_cohort = DATE('2018-07-02')
Database: firebase (snowflake)
Question: Could you please help me get the weekly customer retention rate in September 2018 for new customers who first used our app (first_open event) within the first week starting from September 1st, 2018 (timezone in Shanghai)? The retention rates should cover the following weeks 1, 2, and 3 period after the initial use and display them in column format.
SQL:
WITH analytics_data AS (
  SELECT user_pseudo_id, event_timestamp, event_name, 
    UNIX_MICROS(TIMESTAMP("2018-09-01 00:00:00", "+8:00")) AS start_day,
    3600*1000*1000*24*7 AS one_week_micros
  FROM `firebase-public-project.analytics_153293282.events_*`
  WHERE _table_suffix BETWEEN '20180901' AND '20180930'
)

SELECT
 week_1_cohort / week_0_cohort AS week_1_pct,
 week_2_cohort / week_0_cohort AS week_2_pct,
 week_3_cohort / week_0_cohort AS week_3_pct
FROM (
  WITH week_3_users AS (
    SELECT DISTINCT user_pseudo_id
    FROM analytics_data
    WHERE event_timestamp BETWEEN start_day+(3*one_week_micros) AND start_day+(4*one_week_micros)
  ),
  week_2_users AS (
    SELECT DISTINCT user_pseudo_id
    FROM analytics_data
    WHERE event_timestamp BETWEEN start_day+(2*one_week_micros) AND start_day+(3*one_week_micros)
  ),
  week_1_users AS (
    SELECT DISTINCT user_pseudo_id
    FROM analytics_data
    WHERE event_timestamp BETWEEN start_day+(1*one_week_micros) AND start_day+(2*one_week_micros)
  ), 
  week_0_users AS (
    SELECT DISTINCT user_pseudo_id
    FROM analytics_data
    WHERE event_name = 'first_open'
      AND event_timestamp BETWEEN start_day AND start_day+(1*one_week_micros)
  )
  SELECT 
    (SELECT count(*) 
     FROM week_0_users) AS week_0_cohort,
    (SELECT count(*) 
     FROM week_1_users 
     JOIN week_0_users USING (user_pseudo_id)) AS week_1_cohort,
    (SELECT count(*) 
     FROM week_2_users 
     JOIN week_0_users USING (user_pseudo_id)) AS week_2_cohort,
    (SELECT count(*) 
     FROM week_3_users 
     JOIN week_0_users USING (user_pseudo_id)) AS week_3_cohort
)
Database: firebase (snowflake)
Question: For all users who first opened the app in September 2018 and then uninstalled within seven days, I want to know what percentage of them experienced an app crash (app_exception). The calculation should be done by converting the timestamps to dates first, and then calculating the days to uninstall based on the dates. Only users who uninstalled within 7 days and experienced a crash should be considered in the final percentage.
SQL:
Database: E_commerce (snowflake)
Question: According to the RFM definition document, calculate the average sales per order for each customer within distinct RFM segments, considering only 'delivered' orders. Use the customer unique identifier. Clearly define how to calculate Recency based on the latest purchase timestamp and specify the criteria for classifying RFM segments. The average sales should be computed as the total spend divided by the total number of orders. Please analyze and report the differences in average sales across the RFM segments
SQL:
WITH RecencyScore AS (
    SELECT customer_unique_id,
           MAX(order_purchase_timestamp) AS last_purchase,
           NTILE(5) OVER (ORDER BY MAX(order_purchase_timestamp) DESC) AS recency
    FROM orders
        JOIN customers USING (customer_id)
    WHERE order_status = 'delivered'
    GROUP BY customer_unique_id
),
FrequencyScore AS (
    SELECT customer_unique_id,
           COUNT(order_id) AS total_orders,
           NTILE(5) OVER (ORDER BY COUNT(order_id) DESC) AS frequency
    FROM orders
        JOIN customers USING (customer_id)
    WHERE order_status = 'delivered'
    GROUP BY customer_unique_id
),
MonetaryScore AS (
    SELECT customer_unique_id,
           SUM(price) AS total_spent,
           NTILE(5) OVER (ORDER BY SUM(price) DESC) AS monetary
    FROM orders
        JOIN order_items USING (order_id)
        JOIN customers USING (customer_id)
    WHERE order_status = 'delivered'
    GROUP BY customer_unique_id
),

-- 2. Assign each customer to a group
RFM AS (
    SELECT last_purchase, total_orders, total_spent,
        CASE
            WHEN recency = 1 AND frequency + monetary IN (1, 2, 3, 4) THEN "Champions"
            WHEN recency IN (4, 5) AND frequency + monetary IN (1, 2) THEN "Can't Lose Them"
            WHEN recency IN (4, 5) AND frequency + monetary IN (3, 4, 5, 6) THEN "Hibernating"
            WHEN recency IN (4, 5) AND frequency + monetary IN (7, 8, 9, 10) THEN "Lost"
            WHEN recency IN (2, 3) AND frequency + monetary IN (1, 2, 3, 4) THEN "Loyal Customers"
            WHEN recency = 3 AND frequency + monetary IN (5, 6) THEN "Needs Attention"
            WHEN recency = 1 AND frequency + monetary IN (7, 8) THEN "Recent Users"
            WHEN recency = 1 AND frequency + monetary IN (5, 6) OR
                recency = 2 AND frequency + monetary IN (5, 6, 7, 8) THEN "Potentital Loyalists"
            WHEN recency = 1 AND frequency + monetary IN (9, 10) THEN "Price Sensitive"
            WHEN recency = 2 AND frequency + monetary IN (9, 10) THEN "Promising"
            WHEN recency = 3 AND frequency + monetary IN (7, 8, 9, 10) THEN "About to Sleep"
        END AS RFM_Bucket
    FROM RecencyScore
        JOIN FrequencyScore USING (customer_unique_id)
        JOIN MonetaryScore USING (customer_unique_id)
)

SELECT RFM_Bucket, 
       AVG(total_spent / total_orders) AS avg_sales_per_customer
FROM RFM
GROUP BY RFM_Bucket
Database: E_commerce (snowflake)
Question: Could you tell me the number of orders, average payment per order and customer lifespan in weeks of the 3 custumers with the highest average payment per order, where the lifespan is calculated by subtracting the earliest purchase date from the latest purchase date in days, dividing by seven, and if the result is less than seven days, setting it to 1.0?
SQL:
WITH CustomerData AS (
    SELECT
        customer_unique_id,
        COUNT(DISTINCT orders.order_id) AS order_count,
        SUM(payment_value) AS total_payment,
        JULIANDAY(MIN(order_purchase_timestamp)) AS first_order_day,
        JULIANDAY(MAX(order_purchase_timestamp)) AS last_order_day
    FROM customers
        JOIN orders USING (customer_id)
        JOIN order_payments USING (order_id)
    GROUP BY customer_unique_id
)
SELECT
    customer_unique_id,
    order_count AS PF,
    ROUND(total_payment / order_count, 2) AS AOV,
    CASE
        WHEN (last_order_day - first_order_day) < 7 THEN
            1
        ELSE
            (last_order_day - first_order_day) / 7
        END AS ACL
FROM CustomerData
ORDER BY AOV DESC
LIMIT 3
Database: Baseball (snowflake)
Question: Could you help me calculate the average single career span value in years for all baseball players? Please precise the result as a float number. First, calculate the difference in years, months, and days between the debut and final game dates. For each player, the career span is computed as the sum of the absolute number of years, plus the absolute number of months divided by 12, plus the absolute number of days divided by 365. Round each part to two decimal places before summing. Finally, average the career spans and round the result to a float number.
SQL:
Database: Baseball (snowflake)
Question: I would like to know the given names of baseball players who have achieved the highest value of games played, runs, hits, and home runs, with their corresponding score values.
SQL:
WITH player_stats AS (
    SELECT
        b.player_id,
        p.name_given AS player_name,
        SUM(b.g) AS games_played,
        SUM(b.r) AS runs,
        SUM(b.h) AS hits,
        SUM(b.hr) AS home_runs
    FROM player p
    JOIN batting b ON p.player_id = b.player_id
    GROUP BY b.player_id, p.name_given
)

SELECT 'Games Played' AS Category, player_name AS Player_Name, games_played AS Batting_Table_Topper
FROM player_stats
WHERE games_played = (SELECT MAX(games_played) FROM player_stats)

UNION ALL

SELECT 'Runs' AS Category, player_name AS Player_Name, runs AS Batting_Table_Topper
FROM player_stats
WHERE runs = (SELECT MAX(runs) FROM player_stats)

UNION ALL

SELECT 'Hits' AS Category, player_name AS Player_Name, hits AS Batting_Table_Topper
FROM player_stats
WHERE hits = (SELECT MAX(hits) FROM player_stats)

UNION ALL

SELECT 'Home Runs' AS Category, player_name AS Player_Name, home_runs AS Batting_Table_Topper
FROM player_stats
WHERE home_runs = (SELECT MAX(home_runs) FROM player_stats);
Database: California_Traffic_Collision (snowflake)
Question: Please calculate the fatality rate for motorcycle collisions, separated by helmet usage. Specifically, calculate two percentages: 1) the percentage of motorcyclist fatalities in collisions where parties (drivers or passengers) were wearing helmets, and 2) the percentage of motorcyclist fatalities in collisions where parties were not wearing helmets. For each group, compute this by dividing the total number of motorcyclist fatalities by the total number of collisions involving that group. Use the parties table to determine helmet usage (from party_safety_equipment fields).
SQL:
Database: California_Traffic_Collision (snowflake)
Question: In which year were the two most common causes of traffic accidents different from those in other years?
SQL:
WITH AnnualTotals AS (
    SELECT 
        STRFTIME('%Y', collision_date) AS Year, 
        COUNT(case_id) AS AnnualTotal
    FROM 
        collisions
    GROUP BY 
        Year
),
CategoryTotals AS (
    SELECT 
        STRFTIME('%Y', collision_date) AS Year,
        pcf_violation_category AS Category,
        COUNT(case_id) AS Subtotal
    FROM 
        collisions
    GROUP BY 
        Year, Category
),
CategoryPercentages AS (
    SELECT 
        ct.Year,
        ct.Category,
        ROUND((ct.Subtotal * 100.0) / at.AnnualTotal, 1) AS PercentageOfAnnualRoadIncidents
    FROM 
        CategoryTotals ct
    JOIN 
        AnnualTotals at ON ct.Year = at.Year
),
RankedCategories AS (
    SELECT
        Year,
        Category,
        PercentageOfAnnualRoadIncidents,
        ROW_NUMBER() OVER (PARTITION BY Year ORDER BY PercentageOfAnnualRoadIncidents DESC) AS Rank
    FROM
        CategoryPercentages
),
TopTwoCategories AS (
    SELECT
        Year,
        GROUP_CONCAT(Category, ', ') AS TopCategories
    FROM
        RankedCategories
    WHERE
        Rank <= 2
    GROUP BY
        Year
),
UniqueYear AS (
    SELECT
        Year
    FROM
        TopTwoCategories
    GROUP BY
        TopCategories
    HAVING COUNT(Year) = 1
),
results AS (
SELECT 
    rc.Year, 
    rc.Category, 
    rc.PercentageOfAnnualRoadIncidents
FROM 
    UniqueYear u
JOIN 
    RankedCategories rc ON u.Year = rc.Year
WHERE 
    rc.Rank <= 2
)

SELECT distinct Year FROM results
Database: WWE (snowflake)
Question: For the NXT title that had the shortest match (excluding titles with "title change"), what were the names of the two wrestlers involved?
SQL:
WITH MatchDetails AS (
    SELECT
        b.name AS titles,
        m.duration AS match_duration,
        w1.name || ' vs ' || w2.name AS matches,
        m.win_type AS win_type,
        l.name AS location,
        e.name AS event,
        ROW_NUMBER() OVER (PARTITION BY b.name ORDER BY m.duration ASC) AS rank
    FROM 
        Belts b
    INNER JOIN Matches m ON m.title_id = b.id
    INNER JOIN Wrestlers w1 ON w1.id = m.winner_id
    INNER JOIN Wrestlers w2 ON w2.id = m.loser_id
    INNER JOIN Cards c ON c.id = m.card_id
    INNER JOIN Locations l ON l.id = c.location_id
    INNER JOIN Events e ON e.id = c.event_id
    INNER JOIN Promotions p ON p.id = c.promotion_id
    WHERE
        p.name = 'NXT'
        AND m.duration <> ''
        AND b.name <> ''
        AND b.name NOT IN (
            SELECT name 
            FROM Belts 
            WHERE name LIKE '%title change%'
        )
),
Rank1 AS (
SELECT 
    titles,
    match_duration,
    matches,
    win_type,
    location,
    event
FROM 
    MatchDetails
WHERE 
    rank = 1
)
SELECT
    SUBSTR(matches, 1, INSTR(matches, ' vs ') - 1) AS wrestler1,
    SUBSTR(matches, INSTR(matches, ' vs ') + 4) AS wrestler2
FROM
Rank1
ORDER BY match_duration 
LIMIT 1
Database: IPL (snowflake)
Question: Please help me identify the top 3 bowlers who, in the overs where the maximum runs were conceded in each match, gave up the highest number of runs in a single over across all matches. For each of these bowlers, provide the match in which they conceded these maximum runs. Only consider overs that had the most runs conceded within their respective matches, and among these, determine which bowlers conceded the most runs in a single over overall.
SQL:
Database: IPL (snowflake)
Question: Retrieve the names of players who scored no less than 100 runs in a match while playing for the team that lost that match.
SQL:
-- Step 1: Calculate players' total runs in each match
WITH player_runs AS (
    SELECT 
        bbb.striker AS player_id, 
        bbb.match_id, 
        SUM(bsc.runs_scored) AS total_runs 
    FROM 
        ball_by_ball AS bbb
    JOIN 
        batsman_scored AS bsc
    ON 
        bbb.match_id = bsc.match_id 
        AND bbb.over_id = bsc.over_id 
        AND bbb.ball_id = bsc.ball_id 
        AND bbb.innings_no = bsc.innings_no
    GROUP BY 
        bbb.striker, bbb.match_id
    HAVING 
        SUM(bsc.runs_scored) >= 100
),

-- Step 2: Identify losing teams for each match
losing_teams AS (
    SELECT 
        match_id, 
        CASE 
            WHEN match_winner = team_1 THEN team_2 
            ELSE team_1 
        END AS loser 
    FROM 
        match
),

-- Step 3: Combine the above results to get players who scored 100 or more runs in losing teams
players_in_losing_teams AS (
    SELECT 
        pr.player_id, 
        pr.match_id 
    FROM 
        player_runs AS pr
    JOIN 
        losing_teams AS lt
    ON 
        pr.match_id = lt.match_id
    JOIN 
        player_match AS pm
    ON 
        pr.player_id = pm.player_id 
        AND pr.match_id = pm.match_id 
        AND lt.loser = pm.team_id
)

-- Step 4: Select distinct player names from the player table
SELECT DISTINCT 
    p.player_name 
FROM 
    player AS p
JOIN 
    players_in_losing_teams AS plt
ON 
    p.player_id = plt.player_id
ORDER BY 
    p.player_name;
Database: IPL (snowflake)
Question: Please help me find the names of top 5 players with the highest average runs per match in season 5, along with their batting averages.
SQL:
WITH runs_scored AS (
    SELECT 
        bb.striker AS player_id,
        bb.match_id,
        bs.runs_scored AS runs
    FROM 
        ball_by_ball AS bb
    JOIN 
        batsman_scored AS bs ON bb.match_id = bs.match_id 
            AND bb.over_id = bs.over_id 
            AND bb.ball_id = bs.ball_id 
            AND bb.innings_no = bs.innings_no
    WHERE 
        bb.match_id IN (SELECT match_id FROM match WHERE season_id = 5)
),
total_runs AS (
    SELECT 
        player_id, 
        match_id, 
        SUM(runs) AS total_runs 
    FROM 
        runs_scored 
    GROUP BY 
        player_id, match_id
),
batting_averages AS (
    SELECT 
        player_id, 
        SUM(total_runs) AS runs, 
        COUNT(match_id) AS num_matches,
        ROUND(SUM(total_runs) / CAST(COUNT(match_id) AS FLOAT), 3) AS batting_avg
    FROM 
        total_runs 
    GROUP BY 
        player_id 
    ORDER BY 
        batting_avg DESC 
    LIMIT 5
)
SELECT 
    p.player_name,
    b.batting_avg
FROM 
    player AS p
JOIN 
    batting_averages AS b ON p.player_id = b.player_id
ORDER BY 
    b.batting_avg DESC;
Database: Brazilian_E_Commerce (snowflake)
Question: Please identify the top three customers, based on their customer_unique_id, who have the highest number of delivered orders, and provide the average payment value, city, and state for each of these customers.
SQL:
WITH customer_orders AS (
    SELECT
        c.customer_unique_id,
        COUNT(o.order_id) AS Total_Orders_By_Customers,
        AVG(p.payment_value) AS Average_Payment_By_Customer,
        c.customer_city,
        c.customer_state
    FROM olist_customers c
    JOIN olist_orders o ON c.customer_id = o.customer_id
    JOIN olist_order_payments p ON o.order_id = p.order_id
    WHERE o.order_status = 'delivered'
    GROUP BY c.customer_unique_id, c.customer_city, c.customer_state
)

SELECT 
    Average_Payment_By_Customer,
    customer_city,
    customer_state
FROM customer_orders
ORDER BY Total_Orders_By_Customers DESC
LIMIT 3;
Database: Brazilian_E_Commerce (snowflake)
Question: Could you help me find the sellers who excel in the following categories, considering only delivered orders: the seller with the highest number of distinct customer unique IDs, the seller with the highest profit (calculated as price minus freight value), the seller with the highest number of distinct orders, and the seller with the most 5-star ratings? For each category, please provide the seller ID and the corresponding value, labeling each row with a description of the achievement.
SQL:
Database: Pagila (snowflake)
Question: Could you help me determine which actor starred most frequently in English-language children's category films that were rated either G or PG, had a running time of 120 minutes or less, and were released between 2000 and 2010? Please provide the actor's full name.
SQL:
SELECT
    actor.first_name || ' ' || actor.last_name AS full_name
FROM
    actor
INNER JOIN film_actor ON actor.actor_id = film_actor.actor_id
INNER JOIN film ON film_actor.film_id = film.film_id
INNER JOIN film_category ON film.film_id = film_category.film_id
INNER JOIN category ON film_category.category_id = category.category_id
-- Join with the language table
INNER JOIN language ON film.language_id = language.language_id
WHERE
    category.name = 'Children' AND
    film.release_year BETWEEN 2000 AND 2010 AND
    film.rating IN ('G', 'PG') AND
    language.name = 'English' AND
    film.length <= 120
GROUP BY
    actor.actor_id, actor.first_name, actor.last_name
ORDER BY
    COUNT(film.film_id) DESC
LIMIT 1;
Database: Pagila (snowflake)
Question: Please help me find the film category with the highest total rental hours in cities where the city's name either starts with "A" or contains a hyphen. 
SQL:
SELECT
    category.name
FROM
    category
INNER JOIN film_category USING (category_id)
INNER JOIN film USING (film_id)
INNER JOIN inventory USING (film_id)
INNER JOIN rental USING (inventory_id)
INNER JOIN customer USING (customer_id)
INNER JOIN address USING (address_id)
INNER JOIN city USING (city_id)
WHERE
    LOWER(city.city) LIKE 'a%' OR city.city LIKE '%-%'
GROUP BY
    category.name
ORDER BY
    SUM(CAST((julianday(rental.return_date) - julianday(rental.rental_date)) * 24 AS INTEGER)) DESC
LIMIT
    1;
Database: chinook (snowflake)
Question: Identify the artist with the highest overall sales of albums (tie broken by alphabetical order) and the artist with the lowest overall sales of albums (tie broken by alphabetical order), then calculate the amount each customer spent specifically on those two artists’ albums. Next, compute the average spending for the customers who purchased from the top-selling artist and the average spending for the customers who purchased from the lowest-selling artist, and finally return the absolute difference between these two averages.
SQL:
Database: education_business (snowflake)
Question: Can you provide a list of hardware product segments along with their unique product counts for 2020 in the output, ordered by the highest percentage increase in unique fact sales products from 2020 to 2021?
SQL:
WITH UniqueProducts2020 AS (
    SELECT
        dp.segment,
        COUNT(DISTINCT fsm.product_code) AS unique_products_2020
    FROM
        hardware_fact_sales_monthly fsm
    JOIN
        hardware_dim_product dp ON fsm.product_code = dp.product_code
    WHERE
        fsm.fiscal_year = 2020
    GROUP BY
        dp.segment
),
UniqueProducts2021 AS (
    SELECT
        dp.segment,
        COUNT(DISTINCT fsm.product_code) AS unique_products_2021
    FROM
        hardware_fact_sales_monthly fsm
    JOIN
        hardware_dim_product dp ON fsm.product_code = dp.product_code
    WHERE
        fsm.fiscal_year = 2021
    GROUP BY
        dp.segment
)
SELECT
    spc.segment,
    spc.unique_products_2020 AS product_count_2020
FROM
    UniqueProducts2020 spc
JOIN
    UniqueProducts2021 fup ON spc.segment = fup.segment
ORDER BY
    ((fup.unique_products_2021 - spc.unique_products_2020) * 100.0) / (spc.unique_products_2020) DESC;
Database: complex_oracle (snowflake)
Question: In the United States, for Q4 2019 and Q4 2020, first select only those cities where total sales (with no promotions) rose by at least 20% from Q4 2019 to Q4 2020. Among these cities, rank products by their overall sales (still excluding promotions) in those quarters and take the top 20%. Then compute each top product’s share of total sales in Q4 2019 and Q4 2020 and calculate the difference in share from Q4 2019 to Q4 2020, returning the results in descending order of that share change.
SQL:
Database: complex_oracle (snowflake)
Question: Among all products sold in the United States with promo_id=999, considering only those cities whose sales increased by at least 20% from Q4 2019 (calendar_quarter_id=1772) to Q4 2020 (calendar_quarter_id=1776), which product that ranks in the top 20% of total sales has the smallest percentage-point change in its share of total sales between these two quarters?
SQL:
Database: complex_oracle (snowflake)
Question: What is the average projected monthly sales in USD for France in 2021, considering only product sales with promotions where promo_total_id = 1 and channels where channel_total_id = 1, by taking each product’s monthly sales from 2019 and 2020, calculating the growth rate from 2019 to 2020 for that same product and month, applying this growth rate to project 2021 monthly sales, converting all projected 2021 amounts to USD with the 2021 exchange rates, and finally averaging and listing them by month?
SQL:
Database: complex_oracle (snowflake)
Question: What is the median of the average monthly projected sales in USD for France in 2021, calculated by using the monthly sales data from 2019 and 2020 (filtered by promo_total_id=1 and channel_total_id=1), applying the growth rate from 2019 to 2020 to project 2021, converting to USD based on the currency table, and then determining the monthly averages before finding their median?
SQL:
Database: city_legislation (snowflake)
Question: Please examine our database records for Chinese cities (country_code_2 = 'cn') during July 2021 and identify both the shortest and longest streaks of consecutive date entries. For each date in these streaks, return exactly one record per date along with the corresponding city name. In your output, please ensure the first letter of each city name is capitalized and the rest are lowercase. Display the dates and city names for both the shortest and longest consecutive date streaks, ordered by date.
SQL:
Database: city_legislation (snowflake)
Question: Calculate the number of new cities inserted in April, May, and June for each year from 2021 to 2023. For each month, compute the cumulative running total of cities added for that specific month across the years up to and including the given year (i.e., sum the counts of that month over the years). Additionally, calculate the year-over-year growth percentages for both the monthly total and the running total for each month, comparing each year to the previous year. Present the results only for 2022 and 2023, listing the year, the month, the total number of cities added in that month, the cumulative running total for that month, and the year-over-year growth percentages for both the monthly total and the running total. Use the data from 2021 solely as a baseline for calculating growth rates, and exclude it from the final output.
SQL: