nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: modern_data (snowflake)
Question: For each pizza order, provide a single result row with the row ID, order ID, customer ID, pizza name, and final set of ingredients. The final ingredients are determined by starting with the standard toppings from the pizza’s recipe, removing any excluded toppings, and adding any extra toppings. Present the ingredients in a string starting with the pizza name followed by ': ', with ingredients listed in alphabetical order. Ingredients appearing multiple times (e.g., from standard and extra toppings) should be prefixed with '2x' and listed first, followed by single-occurrence ingredients, both in alphabetical order. Group by row ID, order ID, pizza name, and order time to ensure each order appears once. Sort results by row ID in ascending order. Assign pizza_id 1 to 'Meatlovers' pizzas and pizza_id 2 to all others.
SQL:
Database: modern_data (snowflake)
Question: Calculate the total income from Meat Lovers pizzas priced at $12 and Vegetarian pizzas at $10. Include any extra toppings charged at $1 each. Ensure that canceled orders are filtered out. How much money has Pizza Runner earned in total?
SQL:
WITH get_extras_count AS (
    WITH RECURSIVE split_extras AS (
        SELECT
            order_id,
            TRIM(SUBSTR(extras, 1, INSTR(extras || ',', ',') - 1)) AS each_extra,
            SUBSTR(extras || ',', INSTR(extras || ',', ',') + 1) AS remaining_extras
        FROM
            pizza_clean_customer_orders
        UNION ALL
        SELECT
            order_id,
            TRIM(SUBSTR(remaining_extras, 1, INSTR(remaining_extras, ',') - 1)) AS each_extra,
            SUBSTR(remaining_extras, INSTR(remaining_extras, ',') + 1)
        FROM
            split_extras
        WHERE
            remaining_extras <> ''
    )
    SELECT
        order_id,
        COUNT(each_extra) AS total_extras
    FROM
        split_extras
    GROUP BY
        order_id
),
calculate_totals AS (
    SELECT
        t1.order_id,
        t1.pizza_id,
        SUM(
            CASE
                WHEN pizza_id = 1 THEN 12
                WHEN pizza_id = 2 THEN 10
            END
        ) AS total_price,
        t3.total_extras
    FROM 
        pizza_clean_customer_orders AS t1
    JOIN
        pizza_clean_runner_orders AS t2 
    ON
        t2.order_id = t1.order_id
    LEFT JOIN
        get_extras_count AS t3
    ON
        t3.order_id = t1.order_id
    WHERE
        t2.cancellation IS NULL
    GROUP BY 
        t1.order_id,
        t1.pizza_id,
        t3.total_extras
)
SELECT 
    SUM(total_price) + SUM(total_extras) AS total_income
FROM 
    calculate_totals;
Database: bank_sales_trading (snowflake)
Question: For each customer and each month of 2020, first calculate the month-end balance by adding all deposit amounts and subtracting all withdrawal amounts that occurred during that specific month. Then determine which month in 2020 has the highest count of customers with a positive month-end balance and which month has the lowest count. For each of these two months, compute the average month-end balance across all customers and provide the difference between these two averages
SQL:
Database: bank_sales_trading (snowflake)
Question: For each customer, group all deposits and withdrawals by the first day of each month to obtain a monthly net amount, then calculate each month’s closing balance by cumulatively summing these monthly nets. Next, determine the most recent month’s growth rate by comparing its closing balance to the prior month’s balance, treating deposits as positive and withdrawals as negative, and if the previous month’s balance is zero, the growth rate should be the current month’s balance multiplied by 100. Finally, compute the percentage of customers whose most recent month shows a growth rate of more than 5%.
SQL:
Database: bank_sales_trading (snowflake)
Question: For a bank database with customer transactions, calculate each customer's daily running balance (where deposits add to the balance and other transaction types subtract). For each customer and each day, compute the 30-day rolling average balance (only after having 30 days of data, and treating negative averages as zero). Then group these daily averages by month and find each customer's maximum 30-day average balance within each month. Sum these maximum values across all customers for each month. Consider the first month of each customer's transaction history as the baseline period and exclude it from the final results, presenting monthly totals of these summed maximum 30-day average balances.
SQL:
Database: bank_sales_trading (snowflake)
Question: Can you provide a breakdown of how many times each product was viewed, how many times they were added to the shopping cart, and how many times they were left in the cart without being purchased? Also, give me the count of actual purchases for each product. Ensure that products with a page id in (1, 2, 12, 13) are filtered out.
SQL:
WITH product_viewed AS (
    SELECT
        t1.page_id,
        SUM(CASE WHEN event_type = 1 THEN 1 ELSE 0 END) AS n_page_views,
        SUM(CASE WHEN event_type = 2 THEN 1 ELSE 0 END) AS n_added_to_cart
    FROM
        shopping_cart_page_hierarchy AS t1
    JOIN
        shopping_cart_events AS t2
    ON
        t1.page_id = t2.page_id
    WHERE
        t1.product_id IS NOT NULL
    GROUP BY
        t1.page_id
),
product_purchased AS (
    SELECT
        t2.page_id,
        SUM(CASE WHEN event_type = 2 THEN 1 ELSE 0 END) AS purchased_from_cart
    FROM
        shopping_cart_page_hierarchy AS t1
    JOIN
        shopping_cart_events AS t2
    ON
        t1.page_id = t2.page_id
    WHERE
        t1.product_id IS NOT NULL
        AND EXISTS (
            SELECT
                visit_id
            FROM
                shopping_cart_events
            WHERE
                event_type = 3
                AND t2.visit_id = visit_id
        )
        AND t1.page_id NOT IN (1, 2, 12, 13)
    GROUP BY
        t2.page_id
),
product_abandoned AS (
    SELECT
        t2.page_id,
        SUM(CASE WHEN event_type = 2 THEN 1 ELSE 0 END) AS abandoned_in_cart
    FROM
        shopping_cart_page_hierarchy AS t1
    JOIN
        shopping_cart_events AS t2
    ON
        t1.page_id = t2.page_id
    WHERE
        t1.product_id IS NOT NULL
        AND NOT EXISTS (
            SELECT
                visit_id
            FROM
                shopping_cart_events
            WHERE
                event_type = 3
                AND t2.visit_id = visit_id
        )
        AND t1.page_id NOT IN (1, 2, 12, 13)
    GROUP BY
        t2.page_id
)
SELECT
    t1.page_id,
    t1.page_name,
    t2.n_page_views AS 'number of product being viewed',
    t2.n_added_to_cart AS 'number added to the cart',
    t4.abandoned_in_cart AS 'without being purchased in cart',
    t3.purchased_from_cart AS 'count of actual purchases'
FROM
    shopping_cart_page_hierarchy AS t1
JOIN
    product_viewed AS t2 
ON
    t2.page_id = t1.page_id
JOIN
    product_purchased AS t3 
ON 
    t3.page_id = t1.page_id
JOIN
    product_abandoned AS t4 
ON 
    t4.page_id = t1.page_id;
Database: bank_sales_trading (snowflake)
Question: Please analyze our interest data from September 2018 to August 2019. For each month, calculate the average composition for each interest by dividing the composition by the index value. Identify the interest with the highest average composition value each month and report its average composition as the max index composition for that month. Compute the three-month rolling average of these monthly max index compositions. Ensure the output includes the date, the interest name, the max index composition for that month, the rolling average, and the names and max index compositions of the top interests from one month ago and two months ago.
SQL:
Database: bank_sales_trading (snowflake)
Question: Identify the top 10 and bottom 10 interest categories based on their highest composition values across all months. For each category, display the time(MM-YYYY), interest name, and the composition value
SQL:
WITH get_interest_rank AS (
    SELECT
        t1.month_year,
        t2.interest_name,
        t1.composition,
        RANK() OVER (
            PARTITION BY t2.interest_name
            ORDER BY t1.composition DESC
        ) AS interest_rank
    FROM 
        interest_metrics AS t1
    JOIN 
        interest_map AS t2
    ON 
        t1.interest_id = t2.id
    WHERE 
        t1.month_year IS NOT NULL
),
get_top_10 AS (
    SELECT
        month_year,
        interest_name,
        composition
    FROM 
        get_interest_rank
    WHERE 
        interest_rank = 1
    ORDER BY 
        composition DESC
    LIMIT 10
),
get_bottom_10 AS (
    SELECT
        month_year,
        interest_name,
        composition
    FROM 
        get_interest_rank
    WHERE 
        interest_rank = 1
    ORDER BY 
        composition ASC
    LIMIT 10
)
SELECT * 
FROM 
    get_top_10
UNION
SELECT * 
FROM 
    get_bottom_10
ORDER BY 
    composition DESC;
Database: northwind (snowflake)
Question: Considering only the customers who placed orders in 1998, calculate the total amount each customer spent by summing the unit price multiplied by the quantity of all products in their orders, excluding any discounts. Assign each customer to a spending group based on the customer group thresholds, and determine how many customers are in each spending group and what percentage of the total number of customers who placed orders in 1998 each group represents.
SQL:
Database: Db-IMDB (snowflake)
Question: For each year, calculate the percentage of films that had exclusively female actors (meaning no male actors and no actors with unknown/unspecified gender). Consider actors with gender marked as 'Male' or 'None' as non-female. For the results, display the year, the total number of movies in that year, and the percentage of movies with exclusively female actors. Extract the year from the Movie.year field by taking the last 4 characters and converting to a number.
SQL:
Database: Db-IMDB (snowflake)
Question: I need you to look into the actor collaborations and tell me how many actors have made more films with Yash Chopra than with any other director. This will help us understand his influence on the industry better.
SQL:
WITH YASH_CHOPRAS_PID AS (
    SELECT
        TRIM(P.PID) AS PID
    FROM
        Person P
    WHERE
        TRIM(P.Name) = 'Yash Chopra'
),
NUM_OF_MOV_BY_ACTOR_DIRECTOR AS (
    SELECT
        TRIM(MC.PID) AS ACTOR_PID,
        TRIM(MD.PID) AS DIRECTOR_PID,
        COUNT(DISTINCT TRIM(MD.MID)) AS NUM_OF_MOV
    FROM
        M_Cast MC
    JOIN
        M_Director MD ON TRIM(MC.MID) = TRIM(MD.MID)
    GROUP BY
        ACTOR_PID,
        DIRECTOR_PID
),
NUM_OF_MOVIES_BY_YC AS (
    SELECT
        NM.ACTOR_PID,
        NM.DIRECTOR_PID,
        NM.NUM_OF_MOV AS NUM_OF_MOV_BY_YC
    FROM
        NUM_OF_MOV_BY_ACTOR_DIRECTOR NM
    JOIN
        YASH_CHOPRAS_PID YCP ON NM.DIRECTOR_PID = YCP.PID
),
MAX_MOV_BY_OTHER_DIRECTORS AS (
    SELECT
        ACTOR_PID,
        MAX(NUM_OF_MOV) AS MAX_NUM_OF_MOV
    FROM
        NUM_OF_MOV_BY_ACTOR_DIRECTOR NM
    JOIN
        YASH_CHOPRAS_PID YCP ON NM.DIRECTOR_PID <> YCP.PID
    GROUP BY
        ACTOR_PID
),
ACTORS_MOV_COMPARISION AS (
    SELECT
        NMY.ACTOR_PID,
        CASE WHEN NMY.NUM_OF_MOV_BY_YC > IFNULL(NMO.MAX_NUM_OF_MOV, 0) THEN 'Y' ELSE 'N' END AS MORE_MOV_BY_YC
    FROM
        NUM_OF_MOVIES_BY_YC NMY
    LEFT OUTER JOIN
        MAX_MOV_BY_OTHER_DIRECTORS NMO ON NMY.ACTOR_PID = NMO.ACTOR_PID
)
SELECT
    COUNT(DISTINCT TRIM(P.PID)) AS "Number of actor"
FROM
    Person P
WHERE
    TRIM(P.PID) IN (
        SELECT
            DISTINCT ACTOR_PID
        FROM
            ACTORS_MOV_COMPARISION
        WHERE
            MORE_MOV_BY_YC = 'Y'
    );
Database: BowlingLeague (snowflake)
Question: List the bowlers (including their ID, first name, and last name), match number, game number, handicap score, tournament date, and location for only those bowlers who have won games with a handicap score of 190 or less at all three venues: Thunderbird Lanes, Totem Lanes, and Bolero Lanes. Only include the specific game records where they won with a handicap score of 190 or less at these three locations.
SQL:
Database: school_scheduling (snowflake)
Question: Could you provide a list of last names for all students who have completed English courses (where completion is defined as having a ClassStatus of 2), along with their quintile ranks based on their individual grades in those courses? The quintile should be determined by calculating how many students have grades greater than or equal to each student's grade, then dividing this ranking by the total number of students who completed English courses. The quintiles should be labeled as "First" (top 20%), "Second" (top 21-40%), "Third" (top 41-60%), "Fourth" (top 61-80%), and "Fifth" (bottom 20%). Please sort the results from highest performing quintile to lowest (First to Fifth).
SQL:
Database: EntertainmentAgency (snowflake)
Question: Could you list each musical style with the number of times it appears as a 1st, 2nd, or 3rd preference in a single row per style?
SQL:
SELECT 
  Musical_Styles.StyleName,
  COUNT(RankedPreferences.FirstStyle)
    AS FirstPreference,
  COUNT(RankedPreferences.SecondStyle)
    AS SecondPreference,
  COUNT(RankedPreferences.ThirdStyle)
    AS ThirdPreference
FROM Musical_Styles,
 (SELECT (CASE WHEN
    Musical_Preferences.PreferenceSeq = 1
               THEN Musical_Preferences.StyleID
               ELSE Null END) As FirstStyle,
         (CASE WHEN
    Musical_Preferences.PreferenceSeq = 2
               THEN Musical_Preferences.StyleID
               ELSE Null END) As SecondStyle,
         (CASE WHEN
    Musical_Preferences.PreferenceSeq = 3
               THEN Musical_Preferences.StyleID
               ELSE Null END) AS ThirdStyle
   FROM Musical_Preferences)  AS RankedPreferences
WHERE Musical_Styles.StyleID =
         RankedPreferences.FirstStyle
  OR Musical_Styles.StyleID =
         RankedPreferences.SecondStyle
  OR Musical_Styles.StyleID =
         RankedPreferences.ThirdStyle
GROUP BY StyleID, StyleName
HAVING COUNT(FirstStyle) > 0
     OR     COUNT(SecondStyle) > 0
     OR     COUNT(ThirdStyle) > 0
ORDER BY FirstPreference DESC,
        SecondPreference DESC,
        ThirdPreference DESC, StyleID;
Database: EntertainmentAgency (snowflake)
Question: Given a database of musical styles and user preferences, where Musical_Preferences contains user rankings of musical styles (PreferenceSeq=1 for first choice, PreferenceSeq=2 for second choice, PreferenceSeq=3 for third choice): Calculate a weighted score for each musical style by assigning 3 points for each time it was ranked as first choice, 2 points for each second choice, and 1 point for each third choice ranking. Calculate the total weighted score for each musical style that has been ranked by at least one user. Then, compute the absolute difference between each style's total weighted score and the average total weighted score across all such styles.	
SQL:
Database: bank_sales_trading (snowflake)
Question: Using the "bitcoin_prices" table, please calculate the daily percentage change in trading volume for each ticker from August 1 to August 10, 2021, ensuring that any volume ending in "K" or "M" is accurately converted to thousands or millions, any "-" volume is treated as zero, only non-zero volumes are used to determine the previous day's volume, and the results are ordered by ticker and date.
SQL:
Database: education_business (snowflake)
Question: Which university faculty members' salaries are closest to the average salary for their respective ranks? Please provide the ranks, first names, last names, and salaries.university
SQL:
WITH AvgSalaries AS (
    SELECT 
        facrank AS FacRank,
        AVG(facsalary) AS AvSalary
    FROM 
        university_faculty
    GROUP BY 
        facrank
),
SalaryDifferences AS (
    SELECT 
        university_faculty.facrank AS FacRank, 
        university_faculty.facfirstname AS FacFirstName, 
        university_faculty.faclastname AS FacLastName, 
        university_faculty.facsalary AS Salary, 
        ABS(university_faculty.facsalary - AvgSalaries.AvSalary) AS Diff
    FROM 
        university_faculty
    JOIN 
        AvgSalaries ON university_faculty.facrank = AvgSalaries.FacRank
),
MinDifferences AS (
    SELECT 
        FacRank, 
        MIN(Diff) AS MinDiff
    FROM 
        SalaryDifferences
    GROUP BY 
        FacRank
)
SELECT 
    s.FacRank, 
    s.FacFirstName, 
    s.FacLastName, 
    s.Salary
FROM 
    SalaryDifferences s
JOIN 
    MinDifferences m ON s.FacRank = m.FacRank AND s.Diff = m.MinDiff;
Database: city_legislation (snowflake)
Question: What is the annual retention rate of legislators who began their first term between January 1, 1917 and December 31, 1999, measured as the proportion of this cohort still in office on December 31st for each of the first 20 years following their initial term start? The results should show all 20 periods in sequence regardless of whether any legislators were retained in a particular year.
SQL:
Database: city_legislation (snowflake)
Question: Identify the state abbreviations where, for both male and female legislators, the retention rate remains greater than zero at specific intervals of 0, 2, 4, 6, 8, and 10 years after their first term start date. A legislator is considered retained if they are serving on December 31 of the respective year. Only include states where both gender cohorts maintain non-zero retention rates at all six of these time points during the first decade of service.
SQL:
Database: sqlite-sakila (snowflake)
Question: Could you find out the average percentage of the total lifetime sales (LTV) that occur in the first 7 and 30 days after a customer's initial purchase? Also, include the average total lifetime sales (LTV). Please exclude customers with zero lifetime sales. The 7- and 30-day periods should be based on the exact number of hours-minutes-seconds, not calendar days.
SQL:
Database: sqlite-sakila (snowflake)
Question: Among our top 10 paying customers, can you identify the largest change in payment amounts from one month to the immediately following month? Specifically, please determine for which customer and during which month this maximum month-over-month difference occurred, and provide the difference rounded to two decimal places.
SQL:
WITH result_table AS (
  SELECT 
    strftime('%m', pm.payment_date) AS pay_mon, 
    customer_id,
    COUNT(pm.amount) AS pay_countpermon, 
    SUM(pm.amount) AS pay_amount 
  FROM 
    payment AS pm 
  GROUP BY 
    pay_mon, 
    customer_id
), 
top10_customer AS (
  SELECT 
    customer_id,
    SUM(tb.pay_amount) AS total_payments 
  FROM 
    result_table AS tb 
  GROUP BY 
    customer_id
  ORDER BY 
    SUM(tb.pay_amount) DESC 
  LIMIT 
    10
), 
difference_per_mon AS (
  SELECT 
    pay_mon AS month_number, 
    pay_mon AS month, 
    tb.pay_countpermon, 
    tb.pay_amount, 
    ABS(tb.pay_amount - LAG(tb.pay_amount) OVER (PARTITION BY tb.customer_id)) AS diff 
  FROM 
    result_table tb 
    JOIN top10_customer top ON top.customer_id = tb.customer_id
) 
SELECT 
  month, 
  ROUND(max_diff, 2) AS max_diff 
FROM (
  SELECT 
    month, 
    diff, 
    month_number, 
    MAX(diff) OVER (PARTITION BY month) AS max_diff 
  FROM 
    difference_per_mon
) AS max_per_mon 
WHERE 
  diff = max_diff 
ORDER BY 
  max_diff DESC 
LIMIT 
  1;
Database: sqlite-sakila (snowflake)
Question: Can you identify the year and month with the highest rental orders created by the store's staff for each store? Please list the store ID, the year, the month, and the total rentals for those dates.
SQL:
WITH result_table AS (
  SELECT 
    strftime('%Y', RE.RENTAL_DATE) AS YEAR, 
    strftime('%m', RE.RENTAL_DATE) AS RENTAL_MONTH, 
    ST.STORE_ID, 
    COUNT(RE.RENTAL_ID) AS count 
  FROM 
    RENTAL RE 
    JOIN STAFF ST ON RE.STAFF_ID = ST.STAFF_ID 
  GROUP BY 
    YEAR, 
    RENTAL_MONTH, 
    ST.STORE_ID 
), 
monthly_sales AS (
  SELECT 
    YEAR, 
    RENTAL_MONTH, 
    STORE_ID, 
    SUM(count) AS total_rentals 
  FROM 
    result_table 
  GROUP BY 
    YEAR, 
    RENTAL_MONTH, 
    STORE_ID
),
store_max_sales AS (
  SELECT 
    STORE_ID, 
    YEAR, 
    RENTAL_MONTH, 
    total_rentals, 
    MAX(total_rentals) OVER (PARTITION BY STORE_ID) AS max_rentals 
  FROM 
    monthly_sales
)
SELECT 
  STORE_ID, 
  YEAR, 
  RENTAL_MONTH, 
  total_rentals 
FROM 
  store_max_sales 
WHERE 
  total_rentals = max_rentals
ORDER BY 
  STORE_ID;
Database: delivery_center (snowflake)
Question: Can you identify the hubs that saw more than a 20% increase in finished orders from February to March?
SQL:
WITH february_orders AS (
    SELECT
        h.hub_name AS hub_name,
        COUNT(*) AS orders_february
    FROM 
        orders o 
    LEFT JOIN
        stores s ON o.store_id = s.store_id 
    LEFT JOIN 
        hubs h ON s.hub_id = h.hub_id 
    WHERE o.order_created_month = 2 AND o.order_status = 'FINISHED'
    GROUP BY
        h.hub_name
),
march_orders AS (
    SELECT
        h.hub_name AS hub_name,
        COUNT(*) AS orders_march
    FROM 
        orders o 
    LEFT JOIN
        stores s ON o.store_id = s.store_id 
    LEFT JOIN 
        hubs h ON s.hub_id = h.hub_id 
    WHERE o.order_created_month = 3 AND o.order_status = 'FINISHED'
    GROUP BY
        h.hub_name
)
SELECT
    fo.hub_name
FROM
    february_orders fo
LEFT JOIN 
    march_orders mo ON fo.hub_name = mo.hub_name
WHERE 
    fo.orders_february > 0 AND 
    mo.orders_march > 0 AND
    (CAST((mo.orders_march - fo.orders_february) AS REAL) / CAST(fo.orders_february AS REAL)) > 0.2  -- Filter for hubs with more than a 20% increase
Database: IPL (snowflake)
Question: For each IPL season, identify the top three batsmen with the highest total runs scored and the top three bowlers with the most wickets taken, excluding ‘run out’, ‘hit wicket’, and ‘retired hurt’ dismissals. In the event of ties in runs or wickets, break the tie using the smaller player ID. Then output these six players in matched positions—batsman 1 with bowler 1, batsman 2 with bowler 2, and batsman 3 with bowler 3—in ascending order of the season ID, along with each player’s total runs or wickets.
SQL:
Database: IPL (snowflake)
Question: Find the IDs of players who scored the highest number of partnership runs for each match. The output should include the IDs of two players, each with their individual scores and the total partnership score. For each pair, the player with the higher individual score should be listed as player 1, and the player with the lower score as player 2. In cases where both players have the same score, the player with the higher ID should be player 1, and the player with the lower ID should be player 2. There can be multiple rows for a single match.
SQL:
Database: education_business (snowflake)
Question: Using a Salary Dataset where the salary values need to be cleaned by removing non-numeric characters and converting them to a numeric type, write a detailed SQL query that identifies the top 5 companies by average salary in each of Mumbai, Pune, New Delhi, and Hyderabad, then compares each company’s average salary in those cities to the overall national average salary. The final result should display four columns: Location, Company Name, Average Salary in State, and Average Salary in Country, listing only the top 5 companies in each of the specified locations.
SQL:
Database: IPL (snowflake)
Question: Calculate the total number of wickets taken by each bowler (excluding run-outs and other dismissals not attributed to the bowler), their economy rate (total runs conceded divided by total overs bowled, considering only runs scored off the bat and ignoring any extra runs like wides and no-balls), their strike rate (average number of balls bowled per wicket taken), and their best bowling performance in a single match (the match with the most wickets taken by the bowler, formatted as "wickets-runs" where runs are the runs conceded excluding extras).
SQL:
Database: IPL (snowflake)
Question: For each player, list their ID, name, their most frequent role across all matches, batting hand, bowling skill, total runs scored, total matches played, total times they were dismissed, batting average (total runs divided by total dismissals), highest score in a single match, the number of matches in which they scored at least 30 runs, at least 50 runs, and at least 100 runs, total balls faced in their career, strike rate (total runs divided by total balls faced, multiplied by 100), total wickets taken, economy rate (average runs conceded per over), and their best bowling performance in a single match (most wickets taken in a match, formatted as "wickets taken-runs given", where the best performance is the one with the most wickets, and if tied, the fewest runs conceded). Ignore the extra runs data.
SQL:
Database: stacking (snowflake)
Question: Identify the L1_model associated with each model (specified by name and version) that occurs most frequently for each status ('strong' or 'soft'), along with the number of times it occurs. A model has a 'strong' status if, for any of its steps, the maximum test score among non-'Stack' models is less than the 'Stack' model's test score. It has a 'soft' status if the maximum test score among non-'Stack' models equals the 'Stack' model's test score. Count how many times each L1_model is associated with a 'strong' or 'soft' status across all models, and determine which L1_model has the highest occurrence for each status.
SQL:
Database: oracle_sql (snowflake)
Question: For order 423, identify the product IDs, aisles, and positions from which to pick the exact quantities needed for each order line, ensuring that the total picked quantity for each product matches the cumulative quantities ordered without exceeding the available inventory in warehouse 1. Calculate the quantities to be picked from each location by prioritizing inventory with earlier purchased dates and smaller quantities, and ensure that picking respects the sequence and cumulative quantities of the order lines for products with multiple entries.
SQL:
Database: bank_sales_trading (snowflake)
Question: For weekly-sales data, I need an analysis of our sales performance around mid-June for the years 2018, 2019, and 2020. Specifically, calculate the percentage change in sales between the four weeks leading up to June 15 and the four weeks following June 15 for each year.
SQL:
SELECT 
    before_effect,
    after_effect,
    after_effect - before_effect AS change_amount,
    ROUND(((after_effect * 1.0 / before_effect) - 1) * 100, 2) AS percent_change,
    '2018' AS year
FROM (
    SELECT 
        SUM(CASE WHEN delta_weeks BETWEEN 1 AND 4 THEN sales END) AS after_effect,
        SUM(CASE WHEN delta_weeks BETWEEN -3 AND 0 THEN sales END) AS before_effect
    FROM (
        SELECT 
            week_date,
            ROUND((JULIANDAY(week_date) - JULIANDAY('2018-06-15')) / 7.0) + 1 AS delta_weeks,
            sales 
        FROM cleaned_weekly_sales
    ) add_delta_weeks
) AS add_before_after
UNION ALL
SELECT 
    before_effect,
    after_effect,
    after_effect - before_effect AS change_amount,
    ROUND(((after_effect * 1.0 / before_effect) - 1) * 100, 2) AS percent_change,
    '2019' AS year
FROM (
    SELECT 
        SUM(CASE WHEN delta_weeks BETWEEN 1 AND 4 THEN sales END) AS after_effect,
        SUM(CASE WHEN delta_weeks BETWEEN -3 AND 0 THEN sales END) AS before_effect
    FROM (
        SELECT 
            week_date,
            ROUND((JULIANDAY(week_date) - JULIANDAY('2019-06-15')) / 7.0) + 1 AS delta_weeks,
            sales 
        FROM cleaned_weekly_sales
    ) add_delta_weeks
) AS add_before_after
UNION ALL
SELECT 
    before_effect,
    after_effect,
    after_effect - before_effect AS change_amount,
    ROUND(((after_effect * 1.0 / before_effect) - 1) * 100, 2) AS percent_change,
    '2020' AS year
FROM (
    SELECT 
        SUM(CASE WHEN delta_weeks BETWEEN 1 AND 4 THEN sales END) AS after_effect,
        SUM(CASE WHEN delta_weeks BETWEEN -3 AND 0 THEN sales END) AS before_effect
    FROM (
        SELECT 
            week_date,
            ROUND((JULIANDAY(week_date) - JULIANDAY('2020-06-15')) / 7.0) + 1 AS delta_weeks,
            sales 
        FROM cleaned_weekly_sales
    ) add_delta_weeks
) AS add_before_after
ORDER BY year;
Database: log (snowflake)
Question: For each user session in the activity log table, identify the number of events that occurred before the first '/detail' click or '/complete' conversion, counting only events that have a non-empty search type. Find the sessions with the minimum count of such pre-click/pre-conversion events. If multiple sessions share this minimum count, include all of them in the results. Return each qualifying session along with the corresponding path and search type.
SQL:
Database: f1 (snowflake)
Question: For each year, which driver and which constructor scored the most points? I want the full name of each driver.
SQL:
with year_points as (
    select races.year,
           drivers.forename || ' ' || drivers.surname as driver,
           constructors.name as constructor,
           sum(results.points) as points
    from results
    left join races on results.race_id = races.race_id  -- Ensure these columns exist in your schema
    left join drivers on results.driver_id = drivers.driver_id  -- Ensure these columns exist in your schema
    left join constructors on results.constructor_id = constructors.constructor_id  -- Ensure these columns exist in your schema
    group by races.year, driver
    union
    select races.year,
           null as driver,
           constructors.name as constructor,
           sum(results.points) as points
    from results
    left join races on results.race_id = races.race_id  -- Ensure these columns exist in your schema
    left join drivers on results.driver_id = drivers.driver_id  -- Ensure these columns exist in your schema
    left join constructors on results.constructor_id = constructors.constructor_id  -- Ensure these columns exist in your schema
    group by races.year, constructor
),
max_points as (
    select year,
           max(case when driver is not null then points else null end) as max_driver_points,
           max(case when constructor is not null then points else null end) as max_constructor_points
    from year_points
    group by year
)
select max_points.year,
       drivers_year_points.driver,
       constructors_year_points.constructor
from max_points
left join year_points as drivers_year_points on
    max_points.year = drivers_year_points.year and
    max_points.max_driver_points = drivers_year_points.points and
    drivers_year_points.driver is not null
left join year_points as constructors_year_points on
    max_points.year = constructors_year_points.year and
    max_points.max_constructor_points = constructors_year_points.points and
    constructors_year_points.constructor is not null
order by max_points.year;
Database: f1 (snowflake)
Question: Calculate the overall average first round and average last round of races missed by Formula 1 drivers across all years. Include only drivers who missed fewer than three races in a given year and who switched teams between their appearances immediately before and after their hiatus (i.e., the constructor ID for the race right before their first missed race must be different from the constructor ID for the race right after their last missed race in that year). Do not group results by year; return just the overall averages across the entire dataset.
SQL:
Database: GLOBAL_WEATHER__CLIMATE_DATA_FOR_BI (snowflake)
Question: Assuming today is April 1, 2024, I would like to know the daily snowfall amounts greater than 6 inches for each U.S. postal code during the week ending after the first two full weeks of the previous year. Show the postal code, date, and snowfall amount.
SQL:
WITH timestamps AS
(   
    SELECT
        DATE_TRUNC(year,DATEADD(year,-1,DATE '2024-08-29')) AS ref_timestamp,
        LAST_DAY(DATEADD(week,2 + CAST(WEEKISO(ref_timestamp) != 1 AS INTEGER),ref_timestamp),week) AS end_week,
        DATEADD(day, day_num - 7, end_week) AS date_valid_std
    FROM
    (   
        SELECT
            ROW_NUMBER() OVER (ORDER BY SEQ1()) AS day_num
        FROM
            TABLE(GENERATOR(rowcount => 7))
    ) 
)
SELECT
    country,
    postal_code,
    date_valid_std,
    tot_snowfall_in 
FROM 
    GLOBAL_WEATHER__CLIMATE_DATA_FOR_BI.standard_tile.history_day
NATURAL INNER JOIN
    timestamps
WHERE
    country='US' AND
    tot_snowfall_in > 6.0 
ORDER BY 
    postal_code,date_valid_std
;
Database: GLOBAL_GOVERNMENT (snowflake)
Question: For each year from 2015 to 2020, which Census Zip Code Tabulation Area had the second-highest annual population growth rate? Include only areas with a population estimate of at least 25,000 people in that year (based on 5-Year American Community Survey estimates). For each year, provide the zip code, state abbreviation, and the annual growth rate percentage.
SQL:
Database: FINANCE__ECONOMICS (snowflake)
Question: As of December 31, 2022, list the top 10 active banks with assets exceeding $10 billion, ranked by the highest percentage of uninsured assets, where the percentage is calculated as one minus the value of the '% Insured (Estimated)' variable from quarterly estimates. Provide the names of these banks and their respective percentages of uninsured assets.
SQL:
WITH big_banks AS (
    SELECT id_rssd
    FROM FINANCE__ECONOMICS.CYBERSYN.financial_institution_timeseries
    WHERE variable = 'ASSET'
      AND date = '2022-12-31'
      AND value > 1E10
)
SELECT name
FROM FINANCE__ECONOMICS.CYBERSYN.financial_institution_timeseries AS ts
INNER JOIN FINANCE__ECONOMICS.CYBERSYN.financial_institution_attributes AS att ON (ts.variable = att.variable)
INNER JOIN FINANCE__ECONOMICS.CYBERSYN.financial_institution_entities AS ent ON (ts.id_rssd = ent.id_rssd)
INNER JOIN big_banks ON (big_banks.id_rssd = ts.id_rssd)
WHERE ts.date = '2022-12-31'
  AND att.variable_name = '% Insured (Estimated)'
  AND att.frequency = 'Quarterly'
  AND ent.is_active = True
ORDER BY (1 - value) DESC
LIMIT 10;
Database: FINANCE__ECONOMICS (snowflake)
Question: What was the percentage change in post-market close prices for the Magnificent 7 tech companies from January 1 to June 30, 2024?
SQL:
WITH ytd_performance AS (
  SELECT
    ticker,
    MIN(date) OVER (PARTITION BY ticker) AS start_of_year_date,
    FIRST_VALUE(value) OVER (PARTITION BY ticker ORDER BY date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS start_of_year_price,
    MAX(date) OVER (PARTITION BY ticker) AS latest_date,
    LAST_VALUE(value) OVER (PARTITION BY ticker ORDER BY date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS latest_price
  FROM FINANCE__ECONOMICS.CYBERSYN.stock_price_timeseries
  WHERE
    ticker IN ('AAPL', 'MSFT', 'AMZN', 'GOOGL', 'META', 'TSLA', 'NVDA')
    AND date BETWEEN DATE '2024-01-01' AND DATE '2024-06-30'  -- Adjusted to cover only from the start of 2024 to the end of June 2024
    AND variable_name = 'Post-Market Close'
)
SELECT
  ticker,
  (latest_price - start_of_year_price) / start_of_year_price * 100 AS percentage_change_ytd
FROM
  ytd_performance
GROUP BY
  ticker, start_of_year_date, start_of_year_price, latest_date, latest_price
ORDER BY percentage_change_ytd DESC;
Database: FINANCE__ECONOMICS (snowflake)
Question: For each U.S. state, find how the number of active financial branch entities has changed from March 1, 2020, to December 31, 2021. An entity is considered active on a specific date if its start date is on or before that date and its end date is either null or on or after that date. For each state, calculate the number of entities active on March 1, 2020, the number of entities active on December 31, 2021, and the percentage change in these counts
SQL:
Database: US_REAL_ESTATE (snowflake)
Question: How can we find the shortest straight-line distance in miles between each 'The Home Depot' store and its nearest 'Lowe's Home Improvement' location? Using the US_REAL_ESTATE.CYBERSYN database, join the point_of_interest_index table with point_of_interest_addresses_relationships and us_addresses tables to get geographic coordinates. For each 'The Home Depot' location (identified by its poi_id), calculate its distance to all 'Lowe's Home Improvement' stores using ST_DISTANCE and ST_MAKEPOINT functions, convert the distance from meters to miles (dividing by 1609), and return only the record with the minimum distance for each 'The Home Depot' store using QUALIFY with ROW_NUMBER().
SQL:
Database: WEATHER__ENVIRONMENT (snowflake)
Question: Using data from the FEMA National Flood Insurance Program Claim Index, for each year from 2010 through 2019, what were the total building damage amounts and total contents damage amounts reported under the National Flood Insurance Program for the NFIP community named 'City Of New York,' grouped by each year of loss?
SQL:
SELECT 
    YEAR(claims.date_of_loss)               AS year_of_loss,
    claims.nfip_community_name,
    SUM(claims.building_damage_amount) AS total_building_damage_amount,
    SUM(claims.contents_damage_amount) AS total_contents_damage_amount
FROM WEATHER__ENVIRONMENT.CYBERSYN.fema_national_flood_insurance_program_claim_index claims
WHERE 
    claims.nfip_community_name = 'City Of New York' 
    AND year_of_loss >=2010 AND year_of_loss <=2019
GROUP BY year_of_loss, claims.nfip_community_name
ORDER BY year_of_loss, claims.nfip_community_name;
Database: AMAZON_VENDOR_ANALYTICS__SAMPLE_DATASET (snowflake)
Question: Generate a daily detailed sales report for each product under the 'Manufacturing' distributor view, covering the 30 days leading up to February 6, 2022, by joining the sales, traffic, inventory, and net PPM data on date, ASIN, program, period, and distributor_view. The report must include total ordered units, ordered revenue, average selling price, glance views, conversion rate, shipped units, shipped revenue, average net PPM, average procurable product OOS, total on-hand units and value, net received units and value, open purchase order quantities, unfilled customer ordered units, and average vendor confirmation rate, receive fill rate, sell-through rate, and vendor lead time.
SQL:
Database: US_ADDRESSES__POI (snowflake)
Question: Find the top 10 northernmost addresses in Florida's largest zip code area. What are their address numbers, street names, and types?
SQL:
WITH zip_areas AS (
    SELECT
        geo.geo_id,
        geo.geo_name AS zip,
        states.related_geo_name AS state,
        countries.related_geo_name AS country,
        ST_AREA(TRY_TO_GEOGRAPHY(value)) AS area
    FROM US_ADDRESSES__POI.CYBERSYN.geography_index AS geo
    JOIN US_ADDRESSES__POI.CYBERSYN.geography_relationships AS states
        ON (geo.geo_id = states.geo_id AND states.related_level = 'State')
    JOIN US_ADDRESSES__POI.CYBERSYN.geography_relationships AS countries
        ON (geo.geo_id = countries.geo_id AND countries.related_level = 'Country')
    JOIN US_ADDRESSES__POI.CYBERSYN.geography_characteristics AS chars
        ON (geo.geo_id = chars.geo_id AND chars.relationship_type = 'coordinates_geojson')
    WHERE geo.level = 'CensusZipCodeTabulationArea'
),

zip_area_ranks AS (
    SELECT
        *,
        ROW_NUMBER() OVER (PARTITION BY country, state ORDER BY area DESC, geo_id) AS zip_area_rank
    FROM zip_areas
)

SELECT addr.number, addr.street, addr.street_type
FROM US_ADDRESSES__POI.CYBERSYN.us_addresses AS addr
JOIN zip_area_ranks AS areas
    ON (addr.id_zip = areas.geo_id)
WHERE addr.state = 'FL' AND areas.country = 'United States' AND areas.zip_area_rank = 1
ORDER BY LATITUDE DESC
LIMIT 10;
Database: NETHERLANDS_OPEN_MAP_DATA (snowflake)
Question: A real estate company needs a detailed side-by-side comparison of buildings in Amsterdam and Rotterdam. They require a report showing each building class and subclass, with the total surface area (in square meters) and the total number of buildings for each classification category in both cities. The data should be organized by building class and subclass in ascending order, with Amsterdam and Rotterdam statistics presented in parallel columns to facilitate direct comparison. Can you generate this comprehensive building classification comparison report?
SQL:
Database: NETHERLANDS_OPEN_MAP_DATA (snowflake)
Question: Compare the total road lengths in Amsterdam and Rotterdam by creating a side-by-side analysis of both cities. For each combination of road class and subclass, calculate the total length of roads (in meters) specifically for QUADKEY segments '12020210' and '12020211'. Present the results with columns for class, subclass, Amsterdam's road lengths, and Rotterdam's road lengths.
SQL:
Database: YES_ENERGY__SAMPLE_DATA (snowflake)
Question: Produce a report for ERCOT on October 1, 2022, that combines hourly data on day-ahead and real-time prices from node ID 10000697078, load forecasts (datatypeid 19060) and actual loads, plus wind (forecast datatypeid 9285, actual datatypeid 16) and solar (forecast datatypeid 662, actual datatypeid 650) generation forecasts and actuals from object ID 10000712973. This report should include time zone alignments, peak classifications, and net load calculations, providing insights into daily operational dynamics and efficiency.
SQL:
Database: CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE (snowflake)
Question: Determine the population distribution within each block group relative to its census tract in New York State using 2021 ACS data. Include block group ID, census value, state county tract ID, total tract population, and the population ratio of each block group.
SQL:
 WITH TractPop AS (
    SELECT
        CG."BlockGroupID",
        FCV."CensusValue",
        CG."StateCountyTractID",
        CG."BlockGroupPolygon"
    FROM
        CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE.PUBLIC."Dim_CensusGeography" CG
    JOIN
        CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE.PUBLIC."Fact_CensusValues_ACS2021" FCV
        ON CG."BlockGroupID" = FCV."BlockGroupID"
    WHERE
        CG."StateAbbrev" = 'NY'
        AND FCV."MetricID" = 'B01003_001E'
),

TractGroup AS (
    SELECT
        CG."StateCountyTractID",
        SUM(FCV."CensusValue") AS "TotalTractPop"
    FROM
        CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE.PUBLIC."Dim_CensusGeography" CG
    JOIN
        CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE.PUBLIC."Fact_CensusValues_ACS2021" FCV
        ON CG."BlockGroupID" = FCV."BlockGroupID"
    WHERE
        CG."StateAbbrev" = 'NY'
        AND FCV."MetricID" = 'B01003_001E'
    GROUP BY
        CG."StateCountyTractID"
)

SELECT
    TP."BlockGroupID",
    TP."CensusValue",
    TP."StateCountyTractID",
    TG."TotalTractPop",
    CASE WHEN TG."TotalTractPop" <> 0 THEN TP."CensusValue" / TG."TotalTractPop" ELSE 0 END AS "BlockGroupRatio"
FROM
    TractPop TP
JOIN
    TractGroup TG
    ON TP."StateCountyTractID" = TG."StateCountyTractID";
Database: CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE (snowflake)
Question: What is the New York State ZIP code with the highest number of commuters traveling over one hour, according to 2021 ACS data? Include the zip code, the total commuters, state benchmark for this duration, and state population.
SQL:
WITH Commuters AS (
    SELECT
        GE."ZipCode",
        SUM(CASE WHEN M."MetricID" = 'B08303_013E' THEN F."CensusValueByZip" ELSE 0 END +
            CASE WHEN M."MetricID" = 'B08303_012E' THEN F."CensusValueByZip" ELSE 0 END) AS "Num_Commuters_1Hr_Travel_Time"
    FROM
        CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC."LU_GeographyExpanded" GE
    JOIN
        CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC."Fact_CensusValues_ACS2021_ByZip" F
        ON GE."ZipCode" = F."ZipCode"
    JOIN
        CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC."Dim_CensusMetrics" M
        ON F."MetricID" = M."MetricID"
    WHERE
        GE."PreferredStateAbbrev" = 'NY'
        AND (M."MetricID" = 'B08303_013E' OR M."MetricID" = 'B08303_012E') -- Metric IDs for commuters with 1+ hour travel time
    GROUP BY
        GE."ZipCode"
),

StateBenchmark AS (
    SELECT
        SB."StateAbbrev",
        SUM(SB."StateBenchmarkValue") AS "StateBenchmark_Over1HrTravelTime",
        SB."TotalStatePopulation"
    FROM
        CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC."Fact_StateBenchmark_ACS2021" SB
    WHERE
        SB."MetricID" IN ('B08303_013E', 'B08303_012E')
        AND SB."StateAbbrev" = 'NY'
    GROUP BY
        SB."StateAbbrev", SB."TotalStatePopulation"
)

SELECT
    C."ZipCode",
    SUM(C."Num_Commuters_1Hr_Travel_Time") AS "Total_Commuters_1Hr_Travel_Time",
    SB."StateBenchmark_Over1HrTravelTime",
    SB."TotalStatePopulation",
FROM
    Commuters C
CROSS JOIN
    StateBenchmark SB
GROUP BY
    C."ZipCode", SB."StateBenchmark_Over1HrTravelTime", SB."TotalStatePopulation"
ORDER BY
    "Total_Commuters_1Hr_Travel_Time" DESC
LIMIT 1;