nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: SAN_FRANCISCO_PLUS (snowflake)
Question: Could you provide the details of the top 5 longest bike share trips that started between July 1, 2017, and December 31, 2017, including the trip ID, duration in seconds, start date, start station name, route (derived from start station name to end station name), bike number, subscriber type, member's birth year, the member's current age (calculated using the current year), an age classification based on whether the member is younger than 40, between 40 and 60, or older than 60, the member's gender, and the name of the region of the start station? Please exclude any trips where the start station name, member's birth year, or member's gender is not specified.
SQL:
SELECT
  "trip_id",
  "duration_sec",
  DATE(TO_TIMESTAMP_LTZ("start_date" / 1000000)) AS "star_date", -- 将微秒转换为日期
  "start_station_name",
  CONCAT("start_station_name", ' - ', "end_station_name") AS "route",
  "bike_number",
  "subscriber_type",
  "member_birth_year",
  (EXTRACT(YEAR FROM CURRENT_DATE()) - "member_birth_year") AS "age",
  CASE
    WHEN (EXTRACT(YEAR FROM CURRENT_DATE()) - "member_birth_year") < 40 THEN 'Young (<40 Y.O)'
    WHEN (EXTRACT(YEAR FROM CURRENT_DATE()) - "member_birth_year") BETWEEN 40 AND 60 THEN 'Adult (40-60 Y.O)'
    ELSE 'Senior Adult (>60 Y.O)'
  END AS "age_class",
  "member_gender",
  c."name" AS "region_name"
FROM "SAN_FRANCISCO_PLUS"."SAN_FRANCISCO_BIKESHARE"."BIKESHARE_TRIPS" a
LEFT JOIN "SAN_FRANCISCO_PLUS"."SAN_FRANCISCO_BIKESHARE"."BIKESHARE_STATION_INFO" b 
  ON a."start_station_name" = b."name"
LEFT JOIN "SAN_FRANCISCO_PLUS"."SAN_FRANCISCO_BIKESHARE"."BIKESHARE_REGIONS" c 
  ON b."region_id" = c."region_id"
WHERE TO_TIMESTAMP_LTZ("start_date" / 1000000) BETWEEN '2017-07-01' AND '2017-12-31'
  AND b."name" IS NOT NULL
  AND "member_birth_year" IS NOT NULL
  AND "member_gender" IS NOT NULL
ORDER BY "duration_sec" DESC
LIMIT 5;
Database: san_francisco_plus (snowflake)
Question: Which month in 2017 had the largest absolute difference between cumulative bike usage minutes for customers and subscribers?	Which month (in number) in 2017 had the largest absolute difference between cumulative bike usage minutes (in thousands) for customers and subscribers, based on the trip end dates in the San Francisco bikeshare data?
SQL:
WITH monthly_totals AS (
  SELECT
    SUM(CASE WHEN subscriber_type = 'Customer' THEN duration_sec / 60 ELSE NULL END) AS customer_minutes_sum,
    SUM(CASE WHEN subscriber_type = 'Subscriber' THEN duration_sec / 60 ELSE NULL END) AS subscriber_minutes_sum,
    EXTRACT(MONTH FROM end_date) AS end_month
  FROM
    `bigquery-public-data.san_francisco_bikeshare.bikeshare_trips`
  WHERE
    EXTRACT(YEAR FROM end_date) = 2017
  GROUP BY
    end_month
),

cumulative_totals AS (
  SELECT
    end_month,
    SUM(customer_minutes_sum) OVER (ORDER BY end_month ROWS UNBOUNDED PRECEDING) / 1000 AS cumulative_minutes_cust,
    SUM(subscriber_minutes_sum) OVER (ORDER BY end_month ROWS UNBOUNDED PRECEDING) / 1000 AS cumulative_minutes_sub
  FROM
    monthly_totals
),

differences AS (
  SELECT
    end_month,
    ABS(cumulative_minutes_cust - cumulative_minutes_sub) AS abs_diff
  FROM
    cumulative_totals
)

SELECT
  end_month
FROM
  differences
ORDER BY
  abs_diff DESC
LIMIT 1;
Database: san_francisco_plus (snowflake)
Question: For trips where 'Clay St & Drumm St' occurs before 'Sacramento St & Davis St' in the stop sequence (one direction only), what are the earliest departure times from 'Clay St & Drumm St' and the latest arrival times at 'Sacramento St & Davis St' in the format HH:MM:SS? Please provide the trip headsign for each route.
SQL:
WITH SelectedStops AS (
  SELECT 
      stop_id,
      stop_name
  FROM 
      `bigquery-public-data.san_francisco_transit_muni.stops`
  WHERE 
      stop_name IN ('Clay St & Drumm St', 'Sacramento St & Davis St')
),
FilteredStopTimes AS (
  SELECT 
      st.trip_id, 
      st.stop_id, 
      st.arrival_time, 
      st.departure_time, 
      st.stop_sequence, 
      ss.stop_name
  FROM 
      `bigquery-public-data.san_francisco_transit_muni.stop_times` st
  JOIN 
      SelectedStops ss ON CAST(st.stop_id AS STRING) = ss.stop_id
)
SELECT
    t.trip_headsign,
    MIN(st1.departure_time) AS start_time,
    MAX(st2.arrival_time) AS end_time
FROM 
    `bigquery-public-data.san_francisco_transit_muni.trips` t
JOIN FilteredStopTimes st1 ON t.trip_id = CAST(st1.trip_id AS STRING) AND st1.stop_name = 'Clay St & Drumm St'
JOIN FilteredStopTimes st2 ON t.trip_id = CAST(st2.trip_id AS STRING) AND st2.stop_name = 'Sacramento St & Davis St'
WHERE 
    st1.stop_sequence < st2.stop_sequence
GROUP BY 
    t.trip_headsign;
Database: san_francisco_plus (snowflake)
Question: What is the highest average speed (rounded to 1 decimal, in metric m/s) for bike trips in Berkeley with trip distance greater than 1000 meters?
SQL:
WITH stations AS (
  SELECT station_id
  FROM
    `bigquery-public-data.san_francisco_bikeshare.bikeshare_station_info` AS stainfo
  WHERE stainfo.region_id = (
    SELECT region.region_id
    FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_regions` AS region
    WHERE region.name = "Berkeley"
  )
),
meta_data AS (
    SELECT
        round(st_distance(start_station_geom, end_station_geom), 1) as distancia_metros,
        round(st_distance(start_station_geom, end_station_geom) / duration_sec, 1) as velocidade_media
    FROM
        `bigquery-public-data.san_francisco_bikeshare.bikeshare_trips` AS trips
    WHERE
        cast(trips.start_station_id as string) IN (SELECT station_id FROM stations)
        AND cast(trips.end_station_id as string) IN (SELECT station_id FROM stations)
        AND start_station_latitude IS NOT NULL
        AND start_station_longitude IS NOT NULL
        AND end_station_latitude IS NOT NULL
        AND end_station_longitude IS NOT NULL
        AND st_distance(start_station_geom, end_station_geom) > 1000
    ORDER BY
        velocidade_media DESC
    LIMIT 1
)

SELECT velocidade_media as max_velocity
FROM meta_data;
Database: san_francisco_plus (snowflake)
Question: For each neighborhood in San Francisco where at least one bike share station and at least one crime incident are located, provide the neighborhood name along with the total count of bike share stations and the total number of crime incidents in that neighborhood.
SQL:
WITH station_neighborhoods AS (
   SELECT
       bs.station_id,
       bs.name AS station_name,
       nb.neighborhood
   FROM `bigquery-public-data.san_francisco.bikeshare_stations` bs
   JOIN
       bigquery-public-data.san_francisco_neighborhoods.boundaries nb
   ON 
       ST_Intersects(ST_GeogPoint(bs.longitude, bs.latitude), nb.neighborhood_geom)
),

neighborhood_crime_counts AS (
   SELECT
       neighborhood,
       COUNT(*) AS crime_count
   FROM (
       SELECT
           n.neighborhood
       FROM
           bigquery-public-data.san_francisco.sfpd_incidents i
       JOIN
           bigquery-public-data.san_francisco_neighborhoods.boundaries n
       ON
           ST_Intersects(ST_GeogPoint(i.longitude, i.latitude), n.neighborhood_geom)
   ) AS incident_neighborhoods
   GROUP BY
       neighborhood
)

SELECT
  sn.neighborhood,
  COUNT(station_name) AS station_number,
  ANY_VALUE(ncc.crime_count) AS crime_number
FROM
  station_neighborhoods sn
JOIN
  neighborhood_crime_counts ncc
ON
  sn.neighborhood = ncc.neighborhood
GROUP BY sn.neighborhood
ORDER BY
  crime_number ASC
Database: THELOOK_ECOMMERCE (snowflake)
Question: Generate a monthly report for each product category , where each row corresponds to orders that have a status of 'Complete' and were delivered before the year 2022, grouping by the month and year of delivery. For each category, calculate the total revenue (the sum of sale_price), the total number of completed orders, and compute the month-over-month percentage growth for both revenue and orders by comparing each month’s totals to the previous month’s. Then, for the same orders, aggregate and show the total cost (from product costs), total profit (revenue minus total cost), and finally the profit-to-cost ratio for each month.
SQL:
Database: THELOOK_ECOMMERCE (snowflake)
Question: Based solely on completed orders, calculate the average monthly percentage growth rate in the number of unique orders (counting distinct order IDs) for each product category by comparing each month's count to the previous month within the same category. Identify the product category with the highest average of these monthly order growth rates. Then, for that specific product category, compute the average monthly revenue growth rate by calculating the percentage change in total revenue (sum of sale prices) from month to month and averaging these values over the entire period.
SQL:
Database: THELOOK_ECOMMERCE (snowflake)
Question: From January 1, 2019, to April 30, 2022, how many users are at the youngest age and how many users are at the oldest age for each gender in the e-commerce platform, counting both youngest and oldest users separately for each gender?
SQL:
WITH filtered_users AS (
    SELECT 
        "first_name", 
        "last_name", 
        "gender", 
        "age",
        CAST(TO_TIMESTAMP("created_at" / 1000000.0) AS DATE) AS "created_at"
    FROM 
        "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS"
    WHERE 
        CAST(TO_TIMESTAMP("created_at" / 1000000.0) AS DATE) BETWEEN '2019-01-01' AND '2022-04-30'
),
youngest_ages AS (
    SELECT 
        "gender", 
        MIN("age") AS "age"
    FROM 
        filtered_users
    GROUP BY 
        "gender"
),
oldest_ages AS (
    SELECT 
        "gender", 
        MAX("age") AS "age"
    FROM 
        filtered_users
    GROUP BY 
        "gender"
),
youngest_oldest AS (
    SELECT 
        u."first_name", 
        u."last_name", 
        u."gender", 
        u."age", 
        'youngest' AS "tag"
    FROM 
        filtered_users u
    JOIN 
        youngest_ages y
    ON 
        u."gender" = y."gender" AND u."age" = y."age"
    
    UNION ALL
    
    SELECT 
        u."first_name", 
        u."last_name", 
        u."gender", 
        u."age", 
        'oldest' AS "tag"
    FROM 
        filtered_users u
    JOIN 
        oldest_ages o
    ON 
        u."gender" = o."gender" AND u."age" = o."age"
)
SELECT 
    "tag", 
    "gender", 
    COUNT(*) AS "num"
FROM 
    youngest_oldest
GROUP BY 
    "tag", "gender"
ORDER BY 
    "tag", "gender";
Database: THELOOK_ECOMMERCE (snowflake)
Question: Generate a monthly analysis report for e-commerce sales from June 2019 to December 2019 that includes, for each product category and each month, the total number of orders, total revenue, and total profit, along with their month-over-month growth rates using the data from June 2019 as the basis for calculating growth starting from July 2019. Ensure that all orders are included regardless of their status, and present the results sorted in ascending order by month (formatted as "2019-07") and then by product category. Omitting June 2019 from the final output but using it for the growth calculations.
SQL:
Database: THELOOK_ECOMMERCE (snowflake)
Question: Please create a month-by-month report for the year 2023 that focuses on the 'Sleep & Lounge' category, showing for each month the total sales, total cost, number of complete orders, total profit, and the profit-to-cost ratio, ensuring that the order is marked as 'Complete,' the creation date is between January 1, 2023, and December 31, 2023, and the cost data is accurately associated with the corresponding product through the order items. 
SQL:
WITH d AS (
    SELECT
        a."order_id", 
        TO_CHAR(TO_TIMESTAMP(a."created_at" / 1000000.0), 'YYYY-MM') AS "month",  -- 格式化为年月
        TO_CHAR(TO_TIMESTAMP(a."created_at" / 1000000.0), 'YYYY') AS "year",  -- 格式化为年份
        b."product_id", b."sale_price", c."category", c."cost"
    FROM 
        "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDERS" AS a
    JOIN 
        "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDER_ITEMS" AS b
        ON a."order_id" = b."order_id"
    JOIN 
        "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."PRODUCTS" AS c
        ON b."product_id" = c."id"
    WHERE 
        a."status" = 'Complete'
        AND TO_TIMESTAMP(a."created_at" / 1000000.0) BETWEEN TO_TIMESTAMP('2023-01-01') AND TO_TIMESTAMP('2023-12-31')
        AND c."category" = 'Sleep & Lounge'
),

e AS (
    SELECT 
        "month", 
        "year", 
        "sale_price", 
        "category", 
        "cost",
        SUM("sale_price") OVER (PARTITION BY "month", "category") AS "TPV",
        SUM("cost") OVER (PARTITION BY "month", "category") AS "total_cost",
        COUNT(DISTINCT "order_id") OVER (PARTITION BY "month", "category") AS "TPO",
        SUM("sale_price" - "cost") OVER (PARTITION BY "month", "category") AS "total_profit",
        SUM(("sale_price" - "cost") / "cost") OVER (PARTITION BY "month", "category") AS "Profit_to_cost_ratio"
    FROM 
        d
)

SELECT DISTINCT 
    "month", 
    "category", 
    "TPV", 
    "total_cost", 
    "TPO", 
    "total_profit", 
    "Profit_to_cost_ratio"
FROM 
    e
ORDER BY 
    "month";
Database: THELOOK_ECOMMERCE (snowflake)
Question: Identify the difference in the number of the oldest and youngest users registered between January 1, 2019, and April 30, 2022, from our e-commerce platform data.
SQL:
WITH youngest AS (
    SELECT
        "gender", 
        "id", 
        "first_name", 
        "last_name", 
        "age", 
        'youngest' AS "tag"
    FROM 
        "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS"
    WHERE 
        "age" = (SELECT MIN("age") FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS")
        AND TO_TIMESTAMP("created_at" / 1000000.0) BETWEEN TO_TIMESTAMP('2019-01-01') AND TO_TIMESTAMP('2022-04-30')
    GROUP BY 
        "gender", "id", "first_name", "last_name", "age"
    ORDER BY 
        "gender"
),

oldest AS (
    SELECT
        "gender", 
        "id", 
        "first_name", 
        "last_name", 
        "age", 
        'oldest' AS "tag"
    FROM 
        "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS"
    WHERE 
        "age" = (SELECT MAX("age") FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS")
        AND TO_TIMESTAMP("created_at" / 1000000.0) BETWEEN TO_TIMESTAMP('2019-01-01') AND TO_TIMESTAMP('2022-04-30')
    GROUP BY 
        "gender", "id", "first_name", "last_name", "age"
    ORDER BY 
        "gender"
),

TEMP_record AS (
    SELECT * FROM youngest
    UNION ALL
    SELECT * FROM oldest
)

SELECT 
    SUM(CASE WHEN "age" = (SELECT MAX("age") FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS") THEN 1 END) - 
    SUM(CASE WHEN "age" = (SELECT MIN("age") FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS") THEN 1 END) AS "diff"
FROM 
    TEMP_record;
Database: THELOOK_ECOMMERCE (snowflake)
Question: For each month prior to July 2024, identify the single best-selling product (determined by highest sales volume, with total revenue as a tiebreaker) among all orders with a 'Complete' status and products with non-null brands. Return a report showing the month, product name, brand, category, total sales, rounded total revenue, and order status for these monthly top performers.
SQL:
Database: THELOOK_ECOMMERCE (snowflake)
Question: Can you list the email addresses of the top 10 users who registered in 2019 and made purchases in 2019, ranking them by their highest average order value, where average order value is calculated by multiplying the number of items in each order by the sale price, summing this total across all orders for each user, and then dividing by the total number of orders?
SQL:
WITH
  main AS (
    SELECT
      "id" AS "user_id",
      "email",
      "gender",
      "country",
      "traffic_source"
    FROM
      "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS"
    WHERE
      TO_TIMESTAMP("created_at" / 1000000.0) BETWEEN TO_TIMESTAMP('2019-01-01') AND TO_TIMESTAMP('2019-12-31')
  ),

  daate AS (
    SELECT
      "user_id",
      "order_id",
      CAST(TO_TIMESTAMP("created_at" / 1000000.0) AS DATE) AS "order_date",
      "num_of_item"
    FROM
      "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDERS"
    WHERE
      TO_TIMESTAMP("created_at" / 1000000.0) BETWEEN TO_TIMESTAMP('2019-01-01') AND TO_TIMESTAMP('2019-12-31')
  ),

  orders AS (
    SELECT
      "user_id",
      "order_id",
      "product_id",
      "sale_price",
      "status"
    FROM
      "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDER_ITEMS"
    WHERE
      TO_TIMESTAMP("created_at" / 1000000.0) BETWEEN TO_TIMESTAMP('2019-01-01') AND TO_TIMESTAMP('2019-12-31')
  ),

  nest AS (
    SELECT
      o."user_id",
      o."order_id",
      o."product_id",
      d."order_date",
      d."num_of_item",
      ROUND(o."sale_price", 2) AS "sale_price",
      ROUND(d."num_of_item" * o."sale_price", 2) AS "total_sale"
    FROM
      orders o
    INNER JOIN
      daate d
    ON
      o."order_id" = d."order_id"
    ORDER BY
      o."user_id"
  ),

  type AS (
    SELECT
      "user_id",
      MIN(nest."order_date") AS "cohort_date",
      MAX(nest."order_date") AS "latest_shopping_date",
      DATEDIFF(MONTH, MIN(nest."order_date"), MAX(nest."order_date")) AS "lifespan_months",
      ROUND(SUM("total_sale"), 2) AS "ltv",
      COUNT("order_id") AS "no_of_order"
    FROM
      nest
    GROUP BY
      "user_id"
  ),

  kite AS (
    SELECT
      m."user_id",
      m."email",
      m."gender",
      m."country",
      m."traffic_source",
      EXTRACT(YEAR FROM n."cohort_date") AS "cohort_year",
      n."latest_shopping_date",
      n."lifespan_months",
      n."ltv",
      n."no_of_order",
      ROUND(n."ltv" / n."no_of_order", 2) AS "avg_order_value"
    FROM
      main m
    INNER JOIN
      type n
    ON
      m."user_id" = n."user_id"
  )

SELECT
  "email"
FROM
  kite
ORDER BY
  "avg_order_value" DESC
LIMIT 10;
Database: THELOOK_ECOMMERCE (snowflake)
Question: Please generate a report that, for each month in 2021, provides the number of orders, the number of unique purchasers, and the profit (calculated as the sum of product retail prices minus the sum of product costs), where the orders were placed during 2021 by users who registered in 2021 for inventory items created in 2021, and group the results by the users' country, product department, and product category.
SQL:
WITH
orders_x_order_items AS (
  SELECT orders.*,
         order_items."inventory_item_id",
         order_items."sale_price"
  FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDERS" AS orders
  LEFT JOIN "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDER_ITEMS" AS order_items
  ON orders."order_id" = order_items."order_id"
  WHERE TO_TIMESTAMP_NTZ(orders."created_at" / 1000000) BETWEEN TO_TIMESTAMP_NTZ('2021-01-01') AND TO_TIMESTAMP_NTZ('2021-12-31')
),

orders_x_inventory AS (
  SELECT orders_x_order_items.*,
         inventory_items."product_category",
         inventory_items."product_department",
         inventory_items."product_retail_price",
         inventory_items."product_distribution_center_id",
         inventory_items."cost",
         distribution_centers."name"
  FROM orders_x_order_items
  LEFT JOIN "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."INVENTORY_ITEMS" AS inventory_items
  ON orders_x_order_items."inventory_item_id" = inventory_items."id"
  LEFT JOIN "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."DISTRIBUTION_CENTERS" AS distribution_centers
  ON inventory_items."product_distribution_center_id" = distribution_centers."id"
  WHERE TO_TIMESTAMP_NTZ(inventory_items."created_at" / 1000000) BETWEEN TO_TIMESTAMP_NTZ('2021-01-01') AND TO_TIMESTAMP_NTZ('2021-12-31')
),

orders_x_users AS (
  SELECT orders_x_inventory.*,
         users."country" AS "users_country"
  FROM orders_x_inventory
  LEFT JOIN "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS" AS users
  ON orders_x_inventory."user_id" = users."id"
  WHERE TO_TIMESTAMP_NTZ(users."created_at" / 1000000) BETWEEN TO_TIMESTAMP_NTZ('2021-01-01') AND TO_TIMESTAMP_NTZ('2021-12-31')
)

SELECT 
  DATE_TRUNC('MONTH', TO_DATE(TO_TIMESTAMP_NTZ(orders_x_users."created_at" / 1000000))) AS "reporting_month",
  orders_x_users."users_country",
  orders_x_users."product_department",
  orders_x_users."product_category",
  COUNT(DISTINCT orders_x_users."order_id") AS "n_order",
  COUNT(DISTINCT orders_x_users."user_id") AS "n_purchasers",
  SUM(orders_x_users."product_retail_price") - SUM(orders_x_users."cost") AS "profit"
FROM orders_x_users
GROUP BY 1, 2, 3, 4
ORDER BY "reporting_month";
Database: THELOOK_ECOMMERCE (snowflake)
Question: Can you list the top 5 months from August 2022 to November 2023 where the profit from Facebook-sourced completed orders showed the largest month-over-month increase? Calculate profit as sales minus costs, group by delivery month, and include only orders created between August 2022 and November 2023. Compare each month's profit to its previous month to find the largest increases.
SQL:
WITH 
orders AS (
  SELECT
    "order_id", 
    "user_id", 
    "created_at",
    DATE_TRUNC('MONTH', TO_TIMESTAMP_NTZ("delivered_at" / 1000000)) AS "delivery_month",  -- Converting to timestamp
    "status" 
  FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDERS"
),

order_items AS (
  SELECT 
    "order_id", 
    "product_id", 
    "sale_price" 
  FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."ORDER_ITEMS"
),

products AS (
  SELECT 
    "id", 
    "cost"
  FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."PRODUCTS"
),

users AS (
  SELECT
    "id", 
    "traffic_source" 
  FROM "THELOOK_ECOMMERCE"."THELOOK_ECOMMERCE"."USERS"
),

filter_join AS (
  SELECT 
    orders."order_id",
    orders."user_id",
    order_items."product_id",
    orders."delivery_month",
    orders."status",
    order_items."sale_price",
    products."cost",
    users."traffic_source"
  FROM orders
  JOIN order_items ON orders."order_id" = order_items."order_id"
  JOIN products ON order_items."product_id" = products."id"
  JOIN users ON orders."user_id" = users."id"
  WHERE orders."status" = 'Complete' 
    AND users."traffic_source" = 'Facebook'
    AND TO_TIMESTAMP_NTZ(orders."created_at" / 1000000) BETWEEN TO_TIMESTAMP_NTZ('2022-07-01') AND TO_TIMESTAMP_NTZ('2023-11-30')  -- Include July for calculation
),

monthly_sales AS (
  SELECT 
    "delivery_month",
    "traffic_source",
    SUM("sale_price") AS "total_revenue",
    SUM("sale_price") - SUM("cost") AS "total_profit",
    COUNT(DISTINCT "product_id") AS "product_quantity",
    COUNT(DISTINCT "order_id") AS "orders_quantity",
    COUNT(DISTINCT "user_id") AS "users_quantity"
  FROM filter_join
  GROUP BY "delivery_month", "traffic_source"
)

-- Filter to show only 8th month and onwards, but calculate using July
SELECT 
  current_month."delivery_month",
  COALESCE(
    current_month."total_profit" - previous_month."total_profit", 
    0  -- If there is no previous month (i.e. for 8月), return 0
  ) AS "profit_vs_prior_month"
FROM monthly_sales AS current_month
LEFT JOIN monthly_sales AS previous_month
  ON current_month."traffic_source" = previous_month."traffic_source"
  AND current_month."delivery_month" = DATEADD(MONTH, -1, previous_month."delivery_month")  -- Correctly join to previous month
WHERE current_month."delivery_month" >= '2022-08-01'  -- Only show August and later data, but use July for calculation
ORDER BY "profit_vs_prior_month" DESC
LIMIT 5;
Database: census_bureau_international (snowflake)
Question: Provide a list of the top 10 countries for the year 2020, ordered by the highest percentage of their population under 20 years old. For each country, include the total population under 20 years old, the total midyear population, and the percentage of the population that is under 20 years old.
SQL:
SELECT
  age.country_name,
  SUM(age.population) AS under_25,
  pop.midyear_population AS total,
  ROUND((SUM(age.population) / pop.midyear_population) * 100,2) AS pct_under_25
FROM (
  SELECT
    country_name,
    population,
    country_code
  FROM
    `bigquery-public-data.census_bureau_international.midyear_population_agespecific`
  WHERE
    year =2020
    AND age < 20) age
INNER JOIN (
  SELECT
    midyear_population,
    country_code
  FROM
    `bigquery-public-data.census_bureau_international.midyear_population`
  WHERE
    year = 2020) pop
ON
  age.country_code = pop.country_code
GROUP BY
  1,
  3
ORDER BY
  4 DESC
/* Remove limit for visualization */
LIMIT
  10
Database: census_bureau_international (snowflake)
Question: Which country has the highest percentage of population under the age of 25 in 2017?
SQL:
SELECT
country_name
FROM
(SELECT
  age.country_name,
  SUM(age.population) AS under_25,
  pop.midyear_population AS total,
  ROUND((SUM(age.population) / pop.midyear_population) * 100,2) AS pct_under_25
FROM (
  SELECT
    country_name,
    population,
    country_code
  FROM
    `bigquery-public-data.census_bureau_international.midyear_population_agespecific`
  WHERE
    year =2017
    AND age < 25) age
INNER JOIN (
  SELECT
    midyear_population,
    country_code
  FROM
    `bigquery-public-data.census_bureau_international.midyear_population`
  WHERE
    year = 2017) pop
ON
  age.country_code = pop.country_code
GROUP BY
  1,
  3
ORDER BY
  4 DESC
)
LIMIT
1
Database: covid19_open_data (snowflake)
Question: Which day in March and April had the highest COVID-19 confirmed case growth rate in the United States? The format is MM-DD.
SQL:
WITH us_cases_by_date AS (
  SELECT
    date,
    SUM( cumulative_confirmed ) AS cases
  FROM
    `bigquery-public-data.covid19_open_data.covid19_open_data`
  WHERE
    country_name="United States of America"
    AND date between '2020-03-01' and '2020-04-30'
  GROUP BY
    date
  ORDER BY
    date ASC
 )

, us_previous_day_comparison AS
(SELECT
  date,
  cases,
  LAG(cases) OVER(ORDER BY date) AS previous_day,
  cases - LAG(cases) OVER(ORDER BY date) AS net_new_cases,
  (cases - LAG(cases) OVER(ORDER BY date))*100/LAG(cases) OVER(ORDER BY date) AS percentage_increase
FROM us_cases_by_date
)
SELECT
  FORMAT_DATE('%m-%d', Date) 
FROM
  us_previous_day_comparison
ORDER BY  
  percentage_increase
DESC
LIMIT 1
Database: covid19_open_world_bank (snowflake)
Question: You need to calculate the percentage of each country's population that had been confirmed with COVID-19 by June 30, 2020. The population data for 2018 can be found in the World Bank dataset, and the cumulative COVID-19 confirmed cases data is available in the COVID-19 Open Data dataset. Calculate the percentage of each country's population, that was cumulatively confirmed to have COVID-19
SQL:
WITH
  country_pop AS (
  SELECT
    country_code AS iso_3166_1_alpha_3,
    year_2018 AS population_2018
  FROM
    `bigquery-public-data.world_bank_global_population.population_by_country`)
SELECT
  country_code,
  country_name,
  cumulative_confirmed AS june_confirmed_cases,
  population_2018,
  ROUND(cumulative_confirmed/population_2018 * 100,2) AS case_percent
FROM
  `bigquery-public-data.covid19_open_data.covid19_open_data`
JOIN
  country_pop
USING
  (iso_3166_1_alpha_3)
WHERE
  date = '2020-06-30'
  AND aggregation_level = 0
ORDER BY
  case_percent DESC
Database: covid19_jhu_world_bank (snowflake)
Question: Could you provide, for the United States, France, China, Italy, Spain, Germany, and Iran, the total number of confirmed COVID-19 cases as of April 20, 2020, along with the number of cases per 100,000 people based on their total 2020 populations calculated by summing all relevant population entries from the World Bank data
SQL:
SELECT
  c.country,
  c.total_confirmed_cases,
  (c.total_confirmed_cases / p.population) * 100000 AS cases_per_100k
FROM
  (
    SELECT
      CASE
        WHEN country_region = 'US' THEN 'United States'
        WHEN country_region = 'Iran' THEN 'Iran, Islamic Rep.'
        ELSE country_region
      END AS country,
      SUM(confirmed) AS total_confirmed_cases
    FROM
      `bigquery-public-data.covid19_jhu_csse.summary`
    WHERE
      date = '2020-04-20'
      AND country_region IN ('US', 'France', 'China', 'Italy', 'Spain', 'Germany', 'Iran')
    GROUP BY
      country
  ) AS c
JOIN
  (
    SELECT
      country_name AS country,
      SUM(value) AS population
    FROM
      `bigquery-public-data.world_bank_wdi.indicators_data`
    WHERE
      indicator_code = 'SP.POP.TOTL'
      AND year = 2020
    GROUP BY
      country_name
  ) AS p
ON
  c.country = p.country
ORDER BY
  cases_per_100k DESC
Database: covid19_nyt (snowflake)
Question: Analyze daily new COVID-19 case counts from March to May 2020, identifying the top five states by daily increases. Please compile a ranking based on how often each state appears in these daily top fives. Then, examine the state that ranks fourth overall and identify its top five counties based on their frequency of appearing in the daily top five new case counts.
SQL:
WITH StateCases AS (
    SELECT
        b.state_name,
        b.date,
        b.confirmed_cases - a.confirmed_cases AS daily_new_cases
    FROM 
        (SELECT
            state_name,
            state_fips_code,
            confirmed_cases,
            DATE_ADD(date, INTERVAL 1 DAY) AS date_shift
        FROM
            `bigquery-public-data.covid19_nyt.us_states`
        WHERE
            date >= '2020-02-29' AND date <= '2020-05-30'
        ) a
    JOIN
        `bigquery-public-data.covid19_nyt.us_states` b 
        ON a.state_fips_code = b.state_fips_code AND a.date_shift = b.date
    WHERE
        b.date >= '2020-03-01' AND b.date <= '2020-05-31'
),
RankedStatesPerDay AS (
    SELECT
        state_name,
        date,
        daily_new_cases,
        RANK() OVER (PARTITION BY date ORDER BY daily_new_cases DESC) as rank
    FROM
        StateCases
),
TopStates AS (
    SELECT
        state_name,
        COUNT(*) AS appearance_count
    FROM
        RankedStatesPerDay
    WHERE
        rank <= 5
    GROUP BY
        state_name
    ORDER BY
        appearance_count DESC
),
FourthState AS (
    SELECT
        state_name
    FROM
        TopStates
    LIMIT 1
    OFFSET 3
),
CountyCases AS (
    SELECT
        b.county,
        b.date,
        b.confirmed_cases - a.confirmed_cases AS daily_new_cases
    FROM 
        (SELECT
            county,
            county_fips_code,
            confirmed_cases,
            DATE_ADD(date, INTERVAL 1 DAY) AS date_shift
        FROM
            `bigquery-public-data.covid19_nyt.us_counties`
        WHERE
            date >= '2020-02-29' AND date <= '2020-05-30'
        ) a
    JOIN
        `bigquery-public-data.covid19_nyt.us_counties` b 
        ON a.county_fips_code = b.county_fips_code AND a.date_shift = b.date
    WHERE
        b.date >= '2020-03-01' AND b.date <= '2020-05-31'
        AND b.state_name = (SELECT state_name FROM FourthState)
),
RankedCountiesPerDay AS (
    SELECT
        county,
        date,
        daily_new_cases,
        RANK() OVER (PARTITION BY date ORDER BY daily_new_cases DESC) as rank
    FROM
        CountyCases
),
TopCounties AS (
    SELECT
        county,
        COUNT(*) AS appearance_count
    FROM
        RankedCountiesPerDay
    WHERE
        rank <= 5
    GROUP BY
        county
    ORDER BY
        appearance_count DESC
    LIMIT 5
)
SELECT
    county
FROM
    TopCounties;
Database: covid19_symptom_search (snowflake)
Question: Please calculate the overall percentage change in the average weekly search frequency for the symptom 'Anosmia' across the five New York City counties—Bronx County, Queens County, Kings County, New York County, and Richmond County—by comparing the combined data from January 1, 2019, through December 31, 2019, with the combined data from January 1, 2020, through December 31, 2020.
SQL:
SELECT
  table_2019.avg_symptom_Anosmia_2019,
  table_2020.avg_symptom_Anosmia_2020,
  ((table_2020.avg_symptom_Anosmia_2020 - table_2019.avg_symptom_Anosmia_2019) / table_2019.avg_symptom_Anosmia_2019) * 100 AS avg_increase
FROM (
  SELECT
    AVG(SAFE_CAST(symptom_Anosmia AS FLOAT64)) AS avg_symptom_Anosmia_2020
  FROM
    `bigquery-public-data.covid19_symptom_search.symptom_search_sub_region_2_weekly`
  WHERE
    sub_region_1 = "New York"
    AND sub_region_2 IN ("Bronx County", "Queens County", "Kings County", "New York County", "Richmond County")
    AND date >= '2020-01-01'
    AND date < '2021-01-01'
) AS table_2020,
(
  SELECT
    AVG(SAFE_CAST(symptom_Anosmia AS FLOAT64)) AS avg_symptom_Anosmia_2019
  FROM
    `bigquery-public-data.covid19_symptom_search.symptom_search_sub_region_2_weekly`
  WHERE
    sub_region_1 = "New York"
    AND sub_region_2 IN ("Bronx County", "Queens County", "Kings County", "New York County", "Richmond County")
    AND date >= '2019-01-01'
    AND date < '2020-01-01'
) AS table_2019
Database: covid19_symptom_search (snowflake)
Question: Please calculate the average levels of anxiety and depression symptoms from the weekly country data for the United States during the periods from January 1, 2019, to January 1, 2020, and from January 1, 2020, to January 1, 2021. Then, compute the percentage increase in these average symptom levels from the 2019 period to the 2020 period.
SQL:
SELECT
  table_2019.avg_symptom_Anxiety_2019,
  table_2020.avg_symptom_Anxiety_2020,
  ((table_2020.avg_symptom_Anxiety_2020 - table_2019.avg_symptom_Anxiety_2019)/table_2019.avg_symptom_Anxiety_2019) * 100 AS percent_increase_anxiety,
  table_2019.avg_symptom_Depression_2019,
  table_2020.avg_symptom_Depression_2020,
  ((table_2020.avg_symptom_Depression_2020 - table_2019.avg_symptom_Depression_2019)/table_2019.avg_symptom_Depression_2019) * 100 AS percent_increase_depression
FROM (
  SELECT
    AVG(CAST(symptom_Anxiety AS FLOAT64)) AS avg_symptom_Anxiety_2020,
    AVG(CAST(symptom_Depression AS FLOAT64)) AS avg_symptom_Depression_2020,
  FROM
    `bigquery-public-data.covid19_symptom_search.symptom_search_country_weekly`
  WHERE
    country_region_code = "US"
    AND date >= '2020-01-01'
    AND date <'2021-01-01') AS table_2020,
  (
  SELECT
    AVG(CAST(symptom_Anxiety AS FLOAT64)) AS avg_symptom_Anxiety_2019,
    AVG(CAST(symptom_Depression AS FLOAT64)) AS avg_symptom_Depression_2019,
  FROM
    `bigquery-public-data.covid19_symptom_search.symptom_search_country_weekly`
  WHERE
    country_region_code = "US"
    AND date >= '2019-01-01'
    AND date <'2020-01-01') AS table_2019
Database: covid19_usa (snowflake)
Question: Given the latest population estimates from the 2018 five-year American Community Survey, what is the number of vaccine sites per 1000 people for counties in California?
SQL:
WITH
  num_vaccine_sites_per_county AS (
  SELECT
    facility_sub_region_1 AS us_state,
    facility_sub_region_2 AS us_county,
    facility_sub_region_2_code AS us_county_fips,
    COUNT(DISTINCT facility_place_id) AS num_vaccine_sites
  FROM
    bigquery-public-data.covid19_vaccination_access.facility_boundary_us_all
  WHERE
    STARTS_WITH(facility_sub_region_2_code, "06")
  GROUP BY
    facility_sub_region_1,
    facility_sub_region_2,
    facility_sub_region_2_code ),
  total_population_per_county AS (
  SELECT
    LEFT(geo_id, 5) AS us_county_fips,
    ROUND(SUM(total_pop)) AS total_population
  FROM
    bigquery-public-data.census_bureau_acs.censustract_2018_5yr
  WHERE
    STARTS_WITH(LEFT(geo_id, 5), "06")
  GROUP BY
    LEFT(geo_id, 5) )
SELECT
  * EXCEPT(us_county_fips),
  ROUND((num_vaccine_sites * 1000) / total_population, 2) AS sites_per_1k_ppl
FROM
  num_vaccine_sites_per_county
INNER JOIN
  total_population_per_county
USING
  (us_county_fips)
ORDER BY
  sites_per_1k_ppl ASC
LIMIT
  100;
Database: covid19_usa (snowflake)
Question: Find the top three counties with populations over 50,000, using the 2020 5-year census data, that had the highest COVID-19 case fatality rates on August 27, 2020. For these counties, provide the name, state, median age, total population, number of confirmed COVID-19 cases per 100,000 people, number of deaths per 100,000 people, and the case fatality rate as a percentage
SQL:
WITH population_data AS (
  SELECT
    geo_id,
    median_age,
    total_pop
  FROM
    `bigquery-public-data.census_bureau_acs.county_2020_5yr`
  WHERE
    total_pop > 50000
),
covid_data AS (
  SELECT
    county_fips_code,
    county_name,
    state,
    SUM(confirmed_cases) AS total_cases,
    SUM(deaths) AS total_deaths
  FROM
    `bigquery-public-data.covid19_usafacts.summary`
  WHERE
    date = '2020-08-27'
  GROUP BY
    county_fips_code, county_name, state
)
SELECT
  covid.county_name,
  covid.state,
  pop.median_age,
  pop.total_pop,
  (covid.total_cases / pop.total_pop * 100000) AS confirmed_cases_per_100000,
  (covid.total_deaths / pop.total_pop * 100000) AS deaths_per_100000,
  (covid.total_deaths / covid.total_cases * 100) AS case_fatality_rate
FROM
  covid_data covid
JOIN
  population_data pop ON covid.county_fips_code = pop.geo_id
ORDER BY
  case_fatality_rate DESC
LIMIT 3;
Database: census_bureau_usa (snowflake)
Question: Please find all zip code areas located within 10 kilometers of the coordinates (-122.3321, 47.6062) by joining the 2010 census population data (summing only male and female populations with no age constraints) and the zip code area information, and return each area’s polygon, land and water area in meters, latitude and longitude, state code, state name, city, county, and total population.
SQL:
Database: census_bureau_international (snowflake)
Question: Which top 3 countries had the highest net migration in 2017 among those with an area greater than 500 square kilometers? And what are their migration rates?
SQL:
WITH results AS (
    SELECT
        growth.country_name,
        growth.net_migration,
        CAST(area.country_area as INT64) as country_area
    FROM (
        SELECT
            country_name,
            net_migration,
            country_code
        FROM
            `bigquery-public-data.census_bureau_international.birth_death_growth_rates`
        WHERE
            year = 2017
    ) growth
    INNER JOIN (
        SELECT
            country_area,
            country_code
        FROM
            `bigquery-public-data.census_bureau_international.country_names_area`
        WHERE
            country_area > 500
    ) area
    ON
        growth.country_code = area.country_code
    ORDER BY
        net_migration DESC
    LIMIT 3
)
SELECT country_name, net_migration
FROM results;
Database: census_bureau_acs_1 (snowflake)
Question: Can you find the census tracts in the 36047 area that are among the top 20 for the largest percentage increases in population from 2011 to 2018, are also among the top 20 for the largest absolute increases in median income during the same period, and had over 1,000 residents in each of those years?
SQL:
WITH population_change AS (
    SELECT
        a.geo_id,
        a.total_pop AS pop_2011,
        b.total_pop AS pop_2018,
        ((b.total_pop - a.total_pop) / a.total_pop) * 100 AS population_change_percentage
    FROM
        bigquery-public-data.census_bureau_acs.censustract_2011_5yr a
    JOIN
        bigquery-public-data.census_bureau_acs.censustract_2018_5yr b
    ON
        a.geo_id = b.geo_id
    WHERE 
        a.total_pop > 1000
        AND b.total_pop > 1000
        AND a.geo_id LIKE '36047%'
        AND b.geo_id LIKE '36047%'
    ORDER BY 
        population_change_percentage DESC
    LIMIT 20
),

acs_2018 AS (
    SELECT 
        geo_id, 
        median_income AS median_income_2018
    FROM 
        bigquery-public-data.census_bureau_acs.censustract_2018_5yr  
    WHERE 
        geo_id LIKE '36047%'
        AND total_pop > 1000
),

acs_2011 AS (
    SELECT 
        geo_id, 
        median_income AS median_income_2011
    FROM 
        bigquery-public-data.census_bureau_acs.censustract_2011_5yr 
    WHERE 
        geo_id LIKE '36047%'
    AND total_pop > 1000
),

acs_diff AS (
    SELECT
        a18.geo_id, 
        a18.median_income_2018, 
        a11.median_income_2011,
        (a18.median_income_2018 - a11.median_income_2011) AS median_income_diff
    FROM 
        acs_2018 a18
    JOIN 
        acs_2011 a11
        ON a18.geo_id = a11.geo_id
    WHERE 
        (a18.median_income_2018 - a11.median_income_2011) IS NOT NULL
    ORDER BY 
        (a18.median_income_2018 - a11.median_income_2011) DESC
    LIMIT 20
),

common_geoids AS (
    SELECT population_change.geo_id
    FROM population_change
    JOIN acs_diff ON population_change.geo_id = acs_diff.geo_id
)

SELECT geo_id FROM common_geoids;
Database: census_bureau_acs_1 (snowflake)
Question: Which census tract has witnessed the largest increase in median income between 2015 and 2018 in California? Tell me the tract code.
SQL:
WITH acs_2018 AS (
    SELECT
      geo_id,
      median_income AS median_income_2018
    FROM
      `bigquery-public-data.census_bureau_acs.censustract_2018_5yr` 
),
acs_2015 AS (
    SELECT
      geo_id,
      median_income AS median_income_2015
    FROM
      `bigquery-public-data.census_bureau_acs.censustract_2015_5yr` ),
acs_diff AS (
    SELECT
      a18.geo_id,
      a18.median_income_2018,
      a15.median_income_2015,
      (a18.median_income_2018 - a15.median_income_2015) AS median_income_diff,
    FROM
      acs_2018 a18
    JOIN
      acs_2015 a15
    ON
      a18.geo_id = a15.geo_id
),
max_geo_id AS (
    SELECT
      geo_id
    FROM
      acs_diff
    WHERE
      median_income_diff IS NOT NULL
      AND acs_diff.geo_id in (
        SELECT
          geo_id
        FROM
          `bigquery-public-data.geo_census_tracts.census_tracts_california`
      )
    ORDER BY
      median_income_diff DESC
    LIMIT 1
)
SELECT
    tracts.tract_ce as tract_code
FROM
    max_geo_id
JOIN
    `bigquery-public-data.geo_census_tracts.census_tracts_california` AS tracts
ON
    max_geo_id.geo_id = tracts.geo_id;
Database: census_bureau_acs_1 (snowflake)
Question: Using the 2017 U.S. Census Tract data from the BigQuery public datasets, you need to proportionally allocate each tract's population and income to the zip codes based on the overlapping area between their geographic boundaries. Then, filter the results to include only those zip codes located within a 5-mile radius of a specific point in Washington State, with coordinates at latitude 47.685833°N and longitude -122.191667°W. Finally, calculate the total population and the average individual income for each zip code (rounded to one decimal place) and sort the results by the average individual income in descending order.
SQL:
WITH all_zip_tract_join AS (
  SELECT 
    zips.zip_code, 
    zips.functional_status as zip_functional_status,
    tracts.tract_ce, 
    tracts.geo_id as tract_geo_id, 
    tracts.functional_status as tract_functional_status,
    ST_Area(ST_Intersection(tracts.tract_geom, zips.zip_code_geom))
        / ST_Area(tracts.tract_geom) as tract_pct_in_zip_code
  FROM  
    `bigquery-public-data.geo_census_tracts.us_census_tracts_national` tracts,
    `bigquery-public-data.geo_us_boundaries.zip_codes` zips
  WHERE 
    ST_Intersects(tracts.tract_geom, zips.zip_code_geom)
),
zip_tract_join AS (
  SELECT * FROM all_zip_tract_join WHERE tract_pct_in_zip_code > 0
),
census_totals AS (
  -- convert averages to additive totals
  SELECT 
    geo_id,
    total_pop,
    total_pop * income_per_capita AS total_income 
  FROM 
    `bigquery-public-data.census_bureau_acs.censustract_2017_5yr` 
),
joined AS ( 
  -- join with precomputed census/zip pairs,
  -- compute zip's share of tract
  SELECT 
    zip_code, 
    total_pop * tract_pct_in_zip_code    AS zip_pop,
    total_income * tract_pct_in_zip_code AS zip_income
  FROM census_totals c
  JOIN zip_tract_join ztj
  ON c.geo_id = ztj.tract_geo_id
),
sums AS ( 
  -- aggregate all "pieces" of zip code
  SELECT
    zip_code, 
    SUM(zip_pop) AS zip_pop,
    SUM(zip_income) AS zip_total_inc
  FROM joined 
  GROUP BY zip_code
),
zip_pop_income AS (
    SELECT 
        zip_code, zip_pop, 
        -- convert to averages
        zip_total_inc / zip_pop AS income_per_capita
    FROM sums
),
zipcodes_within_distance as (
    SELECT 
        zip_code, zip_code_geom
    FROM 
        `bigquery-public-data.geo_us_boundaries.zip_codes`
    WHERE
        state_code = 'WA'  -- Washington state code
        AND
        ST_DWithin(
            ST_GeogPoint(-122.191667, 47.685833),
            zip_code_geom,
            8046.72
        )
)
select 
  stats.zip_code,
  ROUND(stats.zip_pop, 1) as zip_population,
  ROUND(stats.income_per_capita, 1) as average_income
from 
  zipcodes_within_distance area
join 
  zip_pop_income stats
on area.zip_code = stats.zip_code
ORDER BY
    average_income DESC;
Database: ncaa_basketball (snowflake)
Question: List the top 5 universities with the most seasons where they achieved the maximum wins in their respective NCAA basketball seasons between 1900-2000, showing each team's total number of such peak-performance seasons, while excluding entries with missing team names.
SQL:
SELECT
  team_name,
  COUNT(*) AS top_performer_count
FROM (
  SELECT
    DISTINCT c2.season,
    c2.market AS team_name
  FROM (
    SELECT
      season AS a,
      MAX(wins) AS win_max
    FROM
      `bigquery-public-data.ncaa_basketball.mbb_historical_teams_seasons`
    WHERE
      season<=2000
      AND season >=1900
    GROUP BY
      season ),
    `bigquery-public-data.ncaa_basketball.mbb_historical_teams_seasons` c2
  WHERE
    win_max = c2.wins
    AND a = c2.season
    AND c2.market IS NOT NULL
  ORDER BY
    c2.season)
GROUP BY
  team_name
ORDER BY
  top_performer_count DESC,
  team_name
LIMIT
  5
Database: ncaa_basketball (snowflake)
Question: Please generate a table from the NCAA basketball dataset that lists the top five records in each of these four categories: (1) Top Venues - the largest venues by seating capacity with Date shown as 'N/A'; (2) Biggest Championship Margins - National Championship games since the 2016 season (season > 2015) with the biggest point margin victories; (3) Highest Scoring Games - games since the 2011 season (season > 2010) with the highest total points scored by both teams combined; and (4) Total Threes - games since the 2011 season (season > 2010) with the highest total three-pointers made by both teams combined. The final table should be organized with columns for Category, Date, Matchup or Venue, and Key Metric, with each category's 5 records presented in descending order of their key metric.
SQL:
Database: ncaa_basketball (snowflake)
Question: For the top five team markets with the highest number of distinct players who scored at least 15 points during the second period of games between 2010 and 2018, provide details of each game they played in NCAA basketball historical tournament matches during the same period, as specified in the data model document.
SQL:
WITH top_teams AS (
  SELECT
    team_market
  FROM (
    SELECT
      team_market,
      player_id AS id,
      SUM(points_scored)
    FROM
      `bigquery-public-data.ncaa_basketball.mbb_pbp_sr`
    WHERE
      season >= 2010 AND season <=2018 AND period = 2
    GROUP BY
      game_id,
      team_market,
      player_id
    HAVING
      SUM(points_scored) >= 15) C
  GROUP BY
    team_market
  HAVING
    COUNT(DISTINCT id) > 5
  ORDER BY
    COUNT(DISTINCT id) DESC
  LIMIT 5
)


SELECT
  season,
  round,
  days_from_epoch,
  game_date,
  day,
  'win' AS label,
  win_seed AS seed,
  win_market AS market,
  win_name AS name,
  win_alias AS alias,
  win_school_ncaa AS school_ncaa,
  lose_seed AS opponent_seed,
  lose_market AS opponent_market,
  lose_name AS opponent_name,
  lose_alias AS opponent_alias,
  lose_school_ncaa AS opponent_school_ncaa
FROM `bigquery-public-data.ncaa_basketball.mbb_historical_tournament_games`
JOIN top_teams ON top_teams.team_market = win_market
WHERE season >= 2010 AND season <=2018

UNION ALL

SELECT
  season,
  round,
  days_from_epoch,
  game_date,
  day,
  'loss' AS label,
  lose_seed AS seed,
  lose_market AS market,
  lose_name AS name,
  lose_alias AS alias,
  lose_school_ncaa AS school_ncaa,
  win_seed AS opponent_seed,
  win_market AS opponent_market,
  win_name AS opponent_name,
  win_alias AS opponent_alias,
  win_school_ncaa AS opponent_school_ncaa
FROM `bigquery-public-data.ncaa_basketball.mbb_historical_tournament_games`
JOIN top_teams ON top_teams.team_market = lose_market
WHERE season >= 2010 AND season <=2018