nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: ncaa_insights (snowflake)
Question: Create a dataset by combining NCAA men's basketball tournament game outcomes from the 2014 season onwards, including both the historical tournament games and the 2018 tournament results, with the corresponding pace and efficiency performance metrics for each team and their opponents from the feature_engineering data. The dataset should include the season, game outcome labels (win or loss), team and opponent seeds, school names, pace and efficiency rankings, statistical values, and the differences between the team's and the opponent's metrics to enable a comprehensive analysis of team and opponent dynamics.
SQL:
WITH outcomes AS (
SELECT

  season, # 1994
  "win" AS label, # our label
  win_seed AS seed, # ranking # this time without seed even
  win_school_ncaa AS school_ncaa,
  lose_seed AS opponent_seed, # ranking
  lose_school_ncaa AS opponent_school_ncaa
FROM `data-to-insights.ncaa.mbb_historical_tournament_games` t
WHERE season >= 2014
UNION ALL

SELECT

  season, # 1994
  "loss" AS label, # our label
  lose_seed AS seed, # ranking
  lose_school_ncaa AS school_ncaa,
  win_seed AS opponent_seed, # ranking
  win_school_ncaa AS opponent_school_ncaa
FROM
`data-to-insights.ncaa.mbb_historical_tournament_games` t
WHERE season >= 2014
UNION ALL

SELECT
  season,
  label,
  seed,
  school_ncaa,
  opponent_seed,
  opponent_school_ncaa
FROM
  `data-to-insights.ncaa.2018_tournament_results`
)
SELECT
o.season,
label,
  seed,
  school_ncaa,
  team.pace_rank,
  team.poss_40min,
  team.pace_rating,
  team.efficiency_rank,
  team.pts_100poss,
  team.efficiency_rating,
  opponent_seed,
  opponent_school_ncaa,
  opp.pace_rank AS opp_pace_rank,
  opp.poss_40min AS opp_poss_40min,
  opp.pace_rating AS opp_pace_rating,
  opp.efficiency_rank AS opp_efficiency_rank,
  opp.pts_100poss AS opp_pts_100poss,
  opp.efficiency_rating AS opp_efficiency_rating,
  opp.pace_rank - team.pace_rank AS pace_rank_diff,
  opp.poss_40min - team.poss_40min AS pace_stat_diff,
  opp.pace_rating - team.pace_rating AS pace_rating_diff,
  opp.efficiency_rank - team.efficiency_rank AS eff_rank_diff,
  opp.pts_100poss - team.pts_100poss AS eff_stat_diff,
  opp.efficiency_rating - team.efficiency_rating AS eff_rating_diff
FROM outcomes AS o
LEFT JOIN `data-to-insights.ncaa.feature_engineering` AS team
ON o.school_ncaa = team.team AND o.season = team.season
LEFT JOIN `data-to-insights.ncaa.feature_engineering` AS opp
ON o.opponent_school_ncaa = opp.team AND o.season = opp.season
Database: bls (snowflake)
Question: Which county in Utah experienced the greatest percentage increase in construction employment from 2000 to 2018, calculated by averaging the employment levels during the third month of each quarter in those years? What is the corresponding percentage increase?
SQL:
WITH utah_code AS (
  SELECT DISTINCT geo_id
  FROM bigquery-public-data.geo_us_boundaries.states
  WHERE state_name = 'Utah'
),
e2000 as(
  SELECT
    AVG(month3_emplvl_23_construction) AS construction_employees_2000,
    geoid
  FROM
    `bigquery-public-data.bls_qcew.2000_*`
  WHERE
    geoid LIKE CONCAT((SELECT geo_id FROM utah_code), '%')
  GROUP BY
    geoid),

e2018 AS (
  SELECT
    AVG(month3_emplvl_23_construction) AS construction_employees_2018,
    geoid,
  FROM
    `bigquery-public-data.bls_qcew.2018_*` e2018
  WHERE
    geoid LIKE CONCAT((SELECT geo_id FROM utah_code), '%')
  GROUP BY
    geoid)

SELECT
  c.county_name AS county,
  (construction_employees_2018 - construction_employees_2000) / construction_employees_2000 * 100 AS increase_rate
FROM
  e2000
JOIN
  e2018 USING (geoid)
JOIN 
  `bigquery-public-data.geo_us_boundaries.counties` c ON c.geo_id = e2018.geoid
WHERE
  c.state_fips_code = (SELECT geo_id FROM utah_code)
ORDER BY
  increase_rate desc
LIMIT 1
Database: bls (snowflake)
Question: Between 1998 and 2017, for Allegheny County in the Pittsburgh area, did the average annual wages for all industries keep pace with the inflation of all consumer items, and what were the respective percentage growth rates (to two decimal places) for wages and the CPI over that period?
SQL:
WITH geo AS (
  SELECT DISTINCT geo_id
  FROM `bigquery-public-data.geo_us_boundaries.counties`
  WHERE county_name = "Allegheny" 
),
avg_wage_1998 AS(
  SELECT
    ROUND(AVG(avg_wkly_wage_10_total_all_industries) * 52, 2) AS wages_1998
  FROM
    `bigquery-public-data.bls_qcew.1998*`
  WHERE
    geoid = (SELECT geo_id FROM geo) --Selecting Allgeheny County
),
    
avg_wage_2017 AS (
  SELECT
    ROUND(AVG(avg_wkly_wage_10_total_all_industries) * 52, 2) AS wages_2017
  FROM
    `bigquery-public-data.bls_qcew.2017*`
  WHERE
    geoid = (SELECT geo_id FROM geo) --Selecting Allgeheny County
),

avg_cpi_1998 AS (
  SELECT
    AVG(value) AS cpi_1998
  FROM
    `bigquery-public-data.bls.cpi_u` c
  WHERE
    year = 1998
    AND item_code in (
      SELECT DISTINCT item_code FROM `bigquery-public-data.bls.cpi_u` WHERE LOWER(item_name) = "all items"
    )
    AND area_code = (
      SELECT DISTINCT area_code FROM `bigquery-public-data.bls.cpi_u` WHERE area_name LIKE '%Pittsburgh%'
    )
), 
-- A104 is the code for Pittsburgh, PA
-- SA0 is the code for all items
    
avg_cpi_2017 AS(
  SELECT
    AVG(value) AS cpi_2017
  FROM
    `bigquery-public-data.bls.cpi_u` c
  WHERE
    year = 2017
    AND item_code in (
      SELECT DISTINCT item_code FROM `bigquery-public-data.bls.cpi_u` WHERE LOWER(item_name) = "all items"
    )
    AND area_code = (
      SELECT DISTINCT area_code FROM `bigquery-public-data.bls.cpi_u` WHERE area_name LIKE '%Pittsburgh%'
    )
)
-- A104 is the code for Pittsburgh, PA
-- SA0 is the code for all items

SELECT
  ROUND((wages_2017 - wages_1998) / wages_1998 * 100, 2) AS wages_percent_change,
  ROUND((cpi_2017 - cpi_1998) / cpi_1998 * 100, 2) AS cpi_percent_change
FROM
  avg_wage_2017,
  avg_wage_1998,
  avg_cpi_2017,
  avg_cpi_1998
Database: google_dei (snowflake)
Question: Can you provide the top three races with the largest percentage differences between Google's 2021 overall hiring data from dar non intersectional hiring and the average percentages in the 2021 BLS data for the technology sectors specifically defined as 'Internet publishing and broadcasting and web search portals,' 'Software publishers,' 'Data processing, hosting, and related services,' or the industry group 'Computer systems design and related services,' along with their respective differences?
SQL:
Database: google_dei (snowflake)
Question: Please calculate the growth rates for Asians, Black people, Latinx people, Native Americans, White people, US women, US men, global women, and global men from 2014 to 2024 concerning the overall workforce.
SQL:
CREATE TEMP FUNCTION GrowthRate(end_value FLOAT64, begin_value FLOAT64)
RETURNS FLOAT64
AS ((end_value - begin_value) / begin_value);

SELECT
  GrowthRate(SUM(IF(report_year=2024, race_asian, 0)),
             SUM(IF(report_year=2014, race_asian, 0))) AS race_asian_growth,
  GrowthRate(SUM(IF(report_year=2024, race_black, 0)),
             SUM(IF(report_year=2014, race_black, 0))) AS race_black_growth,
  GrowthRate(SUM(IF(report_year=2024, race_hispanic_latinx, 0)),
             SUM(IF(report_year=2014, race_hispanic_latinx, 0))) AS race_hispanic_growth,
  GrowthRate(SUM(IF(report_year=2024, race_native_american, 0)),
             SUM(IF(report_year=2014, race_native_american, 0))) AS race_native_american_growth,
  GrowthRate(SUM(IF(report_year=2024, race_white, 0)),
             SUM(IF(report_year=2014, race_white, 0))) AS race_white_growth,
  GrowthRate(SUM(IF(report_year=2024, gender_us_women, 0)),
             SUM(IF(report_year=2014, gender_us_women, 0))) AS gender_us_women_growth,
  GrowthRate(SUM(IF(report_year=2024, gender_us_men, 0)),
             SUM(IF(report_year=2014, gender_us_men, 0))) AS gender_us_men_growth,
  GrowthRate(SUM(IF(report_year=2024, gender_global_women, 0)),
             SUM(IF(report_year=2014, gender_global_women, 0))) AS gender_global_women_growth,
  GrowthRate(SUM(IF(report_year=2024, gender_global_men, 0)),
             SUM(IF(report_year=2014, gender_global_men, 0))) AS gender_global_men_growth
FROM `bigquery-public-data.google_dei.dar_non_intersectional_representation`
WHERE report_year IN (2014, 2024)
  AND workforce = 'overall';
Database: GOOG_BLOCKCHAIN (snowflake)
Question: For each month in the year 2023, how many total transactions occurred (counting all transaction records without removing duplicates of transaction hashes), and how many transactions per second were processed each month, where the transactions-per-second value is calculated by dividing the monthly total count by the exact number of seconds in that month, including the correct leap-year logic if applicable based on the extracted year from the transaction timestamp? Show the monthly transaction count, the computed transactions per second, the year, and the month, and present the rows in descending order of the monthly transaction count.
SQL:
Database: GOOG_BLOCKCHAIN (snowflake)
Question: Retrieve all finalized deposits into Optimism at block 29815485 using the Optimism Standard Bridge, including transaction hash, an Etherscan link (the complete URL), L1 and L2 token addresses, sender and receiver addresses (with leading zeroes stripped), and the deposited amount (converted from hex to decimal). Ensure data is properly formatted and parsed according to Optimism's address and token standards, and remove the prefix '0x' except transaction hash. Note that, the keccak-256 hash of the Ethereum event signature for DepositFinalized is "0x3303facd24627943a92e9dc87cfbb34b15c49b726eec3ad3487c16be9ab8efe8".
SQL:
Database: GOOG_BLOCKCHAIN (snowflake)
Question: Could you retrieve the top three largest USDT transfers on the TRON blockchain by listing the block numbers, source addresses, destination addresses (in TronLink format), and transfer amounts, using the USDT contract address '0xa614f803b6fd780986a42c78ec9c7f77e6ded13c' and the transfer event signature '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', dividing the raw transfer value by 1,000,000 to convert it into the final USDT amount, and then ordering the results by the largest transferred amounts first?
SQL:
Database: DEPS_DEV_V1 (snowflake)
Question: Considering only the latest release versions of NPM package, which packages are the top 8 most popular based on the Github star number, as well as their versions?
SQL:
WITH HighestReleases AS (
    SELECT
        HR."Name",
        HR."Version"
    FROM (
        SELECT
            "Name",
            "Version",
            ROW_NUMBER() OVER (
                PARTITION BY "Name"
                ORDER BY 
                    TO_NUMBER(PARSE_JSON("VersionInfo"):"Ordinal") DESC
            ) AS RowNumber
        FROM
            DEPS_DEV_V1.DEPS_DEV_V1.PACKAGEVERSIONS
        WHERE
            "System" = 'NPM'
            AND TO_BOOLEAN(PARSE_JSON("VersionInfo"):"IsRelease") = TRUE
    ) AS HR
    WHERE HR.RowNumber = 1
),
PVP AS (
    SELECT
        PVP."Name", 
        PVP."Version", 
        PVP."ProjectType", 
        PVP."ProjectName"
    FROM
        DEPS_DEV_V1.DEPS_DEV_V1.PACKAGEVERSIONTOPROJECT AS PVP
    JOIN
        HighestReleases AS HR
    ON
        PVP."Name" = HR."Name"
        AND PVP."Version" = HR."Version"
    WHERE
        PVP."System" = 'NPM'
        AND PVP."ProjectType" = 'GITHUB'
)
SELECT
    PVP."Name", 
    PVP."Version"
FROM
    PVP
JOIN
    DEPS_DEV_V1.DEPS_DEV_V1.PROJECTS AS P
ON
    PVP."ProjectType" = P."Type" 
    AND PVP."ProjectName" = P."Name"
ORDER BY 
    P."StarsCount" DESC
LIMIT 8;
Database: chicago (snowflake)
Question: Calculate the minimum and maximum trip duration in minutes (rounded to the nearest whole number), total number of trips, and average fare for each of six equal quantile groups based on trip duration, considering only trips between 0 and 60 minutes.
SQL:
SELECT
  ROUND(MIN(trip_seconds) / 60, 0) AS min_minutes,
  ROUND(MAX(trip_seconds) / 60, 0) AS max_minutes,
  COUNT(*) AS total_trips,
  AVG(fare) AS average_fare
FROM (
  SELECT
    trip_seconds,
    NTILE(6) OVER (ORDER BY trip_seconds) AS quantile,
    fare
  FROM
    `bigquery-public-data.chicago_taxi_trips.taxi_trips`
  WHERE
    trip_seconds BETWEEN 0 AND 3600
)
GROUP BY
  quantile
ORDER BY
  min_minutes, max_minutes;
Database: chicago (snowflake)
Question: Which three companies had the largest increase in trip numbers between two consecutive months in 2018?
SQL:
select company from
            (select *,
            row_number() over(partition by company order by month_o_month_calc desc) as rownum
            from
            (select *,
            num_trips - lag(num_trips) over(partition by company order by month) as month_o_month_calc
                from
                (SELECT 
                company,
                format_date("%Y-%m", date_sub((cast(trip_start_timestamp as date)), interval 1 month)) as prev_month,
                format_date("%Y-%m", cast(trip_start_timestamp as date)) AS month,
                count(1) AS num_trips
                from `bigquery-public-data.chicago_taxi_trips.taxi_trips`
                where extract(YEAR from trip_start_timestamp) = 2018
                group by company, month, prev_month
                order by company,month)
            order by company, month_o_month_calc desc)
            ) 
        where rownum = 1
        order by month_o_month_calc desc, company 
        limit 3
Database: chicago (snowflake)
Question: Calculate the total number of trips and average fare (formatted to two decimal places) for ten equal-sized quantile groups. Each quantile group should contain approximately the same number of trips based on their rounded trip duration in minutes (between 1-50 minutes). Display each group's time range formatted as "XXm to XXm" (where the numbers are zero-padded to two digits), the total trips count, and the average fare. The time ranges should represent the minimum and maximum duration values within each quantile. Sort the results chronologically by time range. Use NTILE(10) to create the quantiles from the ordered trip durations.
SQL:
SELECT
  FORMAT('%02.0fm to %02.0fm', min_minutes, max_minutes) AS minutes_range,
  SUM(trips) AS total_trips,
  FORMAT('%3.2f', SUM(total_fare) / SUM(trips)) AS average_fare
FROM (
  SELECT
    MIN(duration_in_minutes) OVER (quantiles) AS min_minutes,
    MAX(duration_in_minutes) OVER (quantiles) AS max_minutes,
    SUM(trips) AS trips,
    SUM(total_fare) AS total_fare
  FROM (
    SELECT
      ROUND(trip_seconds / 60) AS duration_in_minutes,
      NTILE(10) OVER (ORDER BY trip_seconds / 60) AS quantile,
      COUNT(1) AS trips,
      SUM(fare) AS total_fare
    FROM
      `bigquery-public-data.chicago_taxi_trips.taxi_trips`
    WHERE
      ROUND(trip_seconds / 60) BETWEEN 1 AND 50
    GROUP BY
      trip_seconds,
      duration_in_minutes )
  GROUP BY
    duration_in_minutes,
    quantile
  WINDOW quantiles AS (PARTITION BY quantile)
  )
GROUP BY
  minutes_range
ORDER BY
  Minutes_range
Database: chicago (snowflake)
Question: What is the highest number of motor vehicle theft incidents that occurred in any single month during 2016?
SQL:

SELECT
  incidents AS highest_monthly_thefts
FROM (
  SELECT
    year,
    EXTRACT(MONTH FROM date) AS month,
    COUNT(1) AS incidents,
    RANK() OVER (PARTITION BY year ORDER BY COUNT(1) DESC) AS ranking
  FROM
    `bigquery-public-data.chicago_crime.crime`
  WHERE
    primary_type = 'MOTOR VEHICLE THEFT'
    AND year = 2016
  GROUP BY
    year,
    month
)
WHERE
  ranking = 1
ORDER BY
  year DESC
LIMIT 1;
Database: chicago (snowflake)
Question: For each year from 2010 to 2016, what is the highest number of motor thefts in one month?
SQL:
SELECT
  year,
  incidents
FROM (
  SELECT
    year,
    EXTRACT(MONTH
    FROM
      date) AS month,
    COUNT(1) AS incidents,
    RANK() OVER (PARTITION BY year ORDER BY COUNT(1) DESC) AS ranking
  FROM
    `bigquery-public-data.chicago_crime.crime`
  WHERE
    primary_type = 'MOTOR VEHICLE THEFT'
    AND year BETWEEN 2010 AND 2016
  GROUP BY
    year,
    month )
WHERE
  ranking = 1
ORDER BY
  year ASC
Database: open_targets_genetics_1 (snowflake)
Question: Find the average, variance, max-min difference, and the QTL source(right study) of the maximum log2(h4/h3) for data where right gene id is "ENSG00000169174", h4 > 0.8, h3 < 0.02, reported trait includes "lesterol levels", right biological feature is "IPSC", and the variant is '1_55029009_C_T'.
SQL:
WITH coloc_stats AS (
  SELECT
    coloc.coloc_log2_h4_h3,
    coloc.right_study AS qtl_source
  FROM
    `open-targets-genetics.genetics.variant_disease_coloc` AS coloc
  JOIN
    `open-targets-genetics.genetics.studies` AS studies
  ON
    coloc.left_study = studies.study_id
  WHERE
    coloc.right_gene_id = "ENSG00000169174"
    AND coloc.coloc_h4 > 0.8
    AND coloc.coloc_h3 < 0.02
    AND studies.trait_reported LIKE "%lesterol levels%"
    AND coloc.right_bio_feature = 'IPSC'
    AND CONCAT(coloc.left_chrom, '_', coloc.left_pos, '_', coloc.left_ref, '_', coloc.left_alt) = '1_55029009_C_T'
),
max_value AS (
  SELECT
    MAX(coloc_log2_h4_h3) AS max_log2_h4_h3
  FROM
    coloc_stats
)

SELECT
  AVG(coloc_log2_h4_h3) AS average,
  VAR_SAMP(coloc_log2_h4_h3) AS variance,
  MAX(coloc_log2_h4_h3) - MIN(coloc_log2_h4_h3) AS max_min_difference,
  (SELECT qtl_source FROM coloc_stats WHERE coloc_log2_h4_h3 = (SELECT max_log2_h4_h3 FROM max_value)) AS qtl_source_of_max
FROM
  coloc_stats;
Database: CYMBAL_INVESTMENTS (snowflake)
Question: How much higher the average intrinsic value is for trades using the feeling-lucky strategy compared to those using the momentum strategy under long-side trades?
SQL:
WITH MomentumTrades AS (
  SELECT
    StrikePrice - LastPx AS priceDifference
  FROM
    `bigquery-public-data.cymbal_investments.trade_capture_report`
  WHERE
    SUBSTR(TargetCompID, 0, 4) = 'MOMO'
    AND (SELECT Side FROM UNNEST(Sides)) = 'LONG'
),

FeelingLuckyTrades AS (
  SELECT
    StrikePrice - LastPx AS priceDifference
  FROM
    `bigquery-public-data.cymbal_investments.trade_capture_report`
  WHERE
    SUBSTR(TargetCompID, 0, 4) = 'LUCK'
    AND (SELECT Side FROM UNNEST(Sides)) = 'LONG'
)

SELECT
  AVG(FeelingLuckyTrades.priceDifference) - AVG(MomentumTrades.priceDifference) AS averageDifference 
FROM
  MomentumTrades,
  FeelingLuckyTrades
Database: CYMBAL_INVESTMENTS (snowflake)
Question: Please collect the information of the top 6 trade report with the highest closing prices. Refer to the document for all the information I want.
SQL:
SELECT
  OrderID AS tradeID,
  MaturityDate AS tradeTimestamp,
  (
    CASE SUBSTR(TargetCompID, 0, 4)
      WHEN 'MOMO' THEN 'Momentum'
      WHEN 'LUCK' THEN 'Feeling Lucky'
      WHEN 'PRED' THEN 'Prediction'
  END
    ) AS algorithm,
  Symbol AS symbol,
  LastPx AS openPrice,
  StrikePrice AS closePrice,
  (
  SELECT
    Side
  FROM
    UNNEST(Sides)
  ) AS tradeDirection,
  (CASE (
    SELECT
      Side
    FROM
      UNNEST(Sides))
      WHEN 'SHORT' THEN -1
      WHEN 'LONG' THEN 1
  END
    ) AS tradeMultiplier
FROM
  `bigquery-public-data.cymbal_investments.trade_capture_report`cv
ORDER BY closePrice DESC
LIMIT 6
Database: usfs_fia (snowflake)
Question: Considering only the latest evaluation group per state for the 'EXPCURR' evaluation type, determine which state has the highest total acreage of timberland and which has the highest total acreage of forestland. For timberland, include plots where the condition status code is 1, the reserved status code is 0, and the site productivity class code is between 1 and 6. For forestland, include plots where the condition status code is 1. Calculate the total acres by summing the adjusted expansion factors for macroplots and subplots, using their respective proportion bases ('MACR' for macroplots and 'SUBP' for subplots) and adjustment factors when greater than zero. For each category (timberland and forestland), provide the state code, evaluation group, state name, and the total acres for the state with the highest total acreage, considering only the latest evaluation group per state.
SQL:
Database: usfs_fia (snowflake)
Question: Based on the condition, plot_tree, and population tables in bigquery-public-data.usfs_fia, for the evaluation_type set to 'EXPCURR' and condition_status_code equal to 1, which states had the largest average subplot size and the largest average macroplot size, respectively, for each of the years 2015, 2016, and 2017? Please include the type of plot (subplot or macroplot), the specific year, the state, and the corresponding average size in your results.
SQL:
Database: gbif (snowflake)
Question: Determine which year had the earliest date after January on which more than 10 sightings of Sterna paradisaea were recorded north of 40 degrees latitude. For each year, find the first day after January with over 10 sightings of this species in that region, and identify the year whose earliest such date is the earliest among all years.
SQL:
WITH tenplus AS (
  SELECT 
    year, 
    EXTRACT(DAYOFYEAR FROM DATE(eventdate)) AS dayofyear, 
    COUNT(*) AS count
  FROM 
    bigquery-public-data.gbif.occurrences
  WHERE 
    eventdate IS NOT NULL 
    AND species = 'Sterna paradisaea' 
    AND decimallatitude > 40.0 
    AND month > 1
  GROUP BY 
    year, 
    eventdate
  HAVING 
    COUNT(*) > 10
)

SELECT 
  year AS year
FROM 
  tenplus
GROUP BY 
  year
ORDER BY 
  MIN(dayofyear)
LIMIT 1;
Database: NOAA_PORTS (snowflake)
Question: Can you provide a comprehensive list of all ports in region number 6585 that lie within U.S. state boundaries and have been affected by named storms in the North Atlantic basin with wind speeds of at least 35 knots and a Saffir-Simpson classification of at least minimal tropical storm strength, including for each port its name, the state name, the distinct years in which storms occurred, the total count of distinct storms, the distinct storm names, the average storm category, the average wind speed, and the respective geometries for both the port and the tropical storm areas?
SQL:
Database: sunroof_solar (snowflake)
Question: Please provide a detailed comparison of the solar potential for each state, distinguishing between postal code and census tract levels. For each state, include the total number of buildings available for solar installations, the average percentage of Google Maps area covered by Project Sunroof, the average percentage of that coverage which is suitable for solar, the total potential panel count, the total kilowatt capacity, the energy generation potential, the carbon dioxide offset, the current number of buildings with solar panels, and the gap in potential installations calculated by adjusting the total qualified buildings with the coverage and suitability percentages and subtracting the current installations.
SQL:
Database: gnomAD (snowflake)
Question: Identify which start positions are associated with missense variants in the BRCA1 gene on chromosome 17, where the reference base is 'C' and the alternate base is 'T'. Using data from the gnomAD v2.1.1 version.
SQL:
WITH gene_region AS (
  SELECT 
    MIN(start_position) AS start_pos, 
    MAX(end_position) AS end_pos
  FROM `bigquery-public-data.gnomAD.v2_1_1_genomes__chr17` AS main_table
  WHERE EXISTS (
    SELECT 1 
    FROM UNNEST(main_table.alternate_bases) AS alternate_bases
    WHERE EXISTS (
      SELECT 1 
      FROM UNNEST(alternate_bases.vep) AS vep
      WHERE vep.SYMBOL = 'BRCA1'
    )
  )
)


SELECT 
  DISTINCT start_position
FROM `bigquery-public-data.gnomAD.v2_1_1_genomes__chr17` AS main_table,
     UNNEST(main_table.alternate_bases) AS alternate_bases,
     UNNEST(alternate_bases.vep) AS vep,
     gene_region
WHERE main_table.start_position >= gene_region.start_pos
  AND main_table.start_position <= gene_region.end_pos
  AND REGEXP_CONTAINS(vep.Consequence, r"missense_variant")
  AND reference_bases = "C"
  AND alternate_bases.alt = "T"
Database: gnomAD (snowflake)
Question: Using the gnomAD v2.1.1 genomes data for chromosome 17, determine the smallest start position and largest end position of any variant whose nested VEP annotations contain the symbol 'BRCA1'. Then, for all variants whose positions fall within that gene region, retrieve the 'Protein_position' values only if the 'Consequence' includes 'missense_variant', sort them in ascending order by 'Protein_position', and finally output the first such result.
SQL:
Database: gnomAD (snowflake)
Question: Generate summary statistics on genetic variants in the region between positions 55039447 and 55064852 on chromosome 1. This includes the number of variants, the total allele count, the total number of alleles, and distinct gene symbols (using Variant Effect Predictor, VEP, for gene annotation). Additionally, compute the density of mutations by dividing the length of the region by the number of variants.  Using data from the gnomAD v3 version.
SQL:
WITH summary_stats AS (
  SELECT
    COUNT(1) AS num_variants,
    SUM((SELECT alt.AC FROM UNNEST(alternate_bases) AS alt)) AS sum_AC,
    SUM(AN) AS sum_AN,
    -- Also include some information from Variant Effect Predictor (VEP).
    STRING_AGG(DISTINCT (SELECT annot.symbol FROM UNNEST(alternate_bases) AS alt,
                                               UNNEST(vep) AS annot LIMIT 1), ', ') AS genes
  FROM bigquery-public-data.gnomAD.v3_genomes__chr1 AS main_table
  WHERE start_position >= 55039447 AND start_position <= 55064852
)
SELECT
  ROUND((55064852 - 55039447) / num_variants, 3) AS burden_of_mutation,
  *
FROM summary_stats;
Database: GOOGLE_TRENDS (snowflake)
Question: Based on the most recent refresh date, identify the top-ranked rising search term for the week that is exactly one year prior to the latest available week in the dataset.
SQL:
WITH LatestWeek AS (
    SELECT
        DATEADD(WEEK, -52, MAX("week")) AS "last_year_week"
    FROM
        GOOGLE_TRENDS.GOOGLE_TRENDS.TOP_RISING_TERMS
),
LatestRefreshDate AS (
    SELECT
        MAX("refresh_date") AS "latest_refresh_date"
    FROM
        GOOGLE_TRENDS.GOOGLE_TRENDS.TOP_RISING_TERMS
),
RankedTerms AS (
    SELECT
        "term",
        "week",
        CASE WHEN "score" IS NULL THEN NULL ELSE "dma_name" END AS "dma_name",
        "rank",
        "score",
        ROW_NUMBER() OVER (
            PARTITION BY "term", "week"
            ORDER BY "score" DESC
        ) AS rn
    FROM
        GOOGLE_TRENDS.GOOGLE_TRENDS.TOP_RISING_TERMS
    WHERE
        "week" = (SELECT "last_year_week" FROM LatestWeek)
        AND "refresh_date" = (SELECT "latest_refresh_date" FROM LatestRefreshDate)
)

SELECT
    "term"
FROM
    RankedTerms
WHERE
    rn = 1
ORDER BY
    "rank"
LIMIT 1;
Database: nhtsa_traffic_fatalities_plus (snowflake)
Question: According to the 2015 and 2016 accident and driver distraction, and excluding cases where the driver’s distraction status is recorded as 'Not Distracted,' 'Unknown if Distracted,' or 'Not Reported,' how many traffic accidents per 100,000 people were caused by driver distraction in each U.S. state for those two years, based on 2010 census population data, and which five states each year had the highest rates?
SQL:
SELECT * FROM
(
SELECT
  '2015' AS year,
  COUNT(a.consecutive_number) AS total,
  a.state_name AS state,
  c.state_pop AS population,
  (COUNT(a.consecutive_number) / c.state_pop * 100000) AS rate_per_100000
FROM
  `bigquery-public-data.nhtsa_traffic_fatalities.accident_2015` a
JOIN
  `bigquery-public-data.nhtsa_traffic_fatalities.distract_2015` b
ON
  a.consecutive_number = b.consecutive_number
JOIN (
  SELECT
    SUM(d.population) AS state_pop,
    e.state_name AS state
  FROM
    `bigquery-public-data.census_bureau_usa.population_by_zip_2010` d
  JOIN
    `bigquery-public-data.utility_us.zipcode_area` e
  ON
    d.zipcode = e.zipcode
  GROUP BY
    state ) c
ON
  c.state = a.state_name
WHERE
  b.driver_distracted_by_name NOT IN ('Not Distracted', 'Unknown if Distracted', 'Not Reported')
GROUP BY
  state,
  population,
  c.state_pop
ORDER BY
  rate_per_100000 DESC
LIMIT 5
)
UNION ALL
(
SELECT
  '2016' AS year,
  COUNT(a.consecutive_number) AS total,
  a.state_name AS state,
  c.state_pop AS population,
  (COUNT(a.consecutive_number) / c.state_pop * 100000) AS rate_per_100000
FROM
  `bigquery-public-data.nhtsa_traffic_fatalities.accident_2016` a
JOIN
  `bigquery-public-data.nhtsa_traffic_fatalities.distract_2016` b
ON
  a.consecutive_number = b.consecutive_number
JOIN (
  SELECT
    SUM(d.population) AS state_pop,
    e.state_name AS state
  FROM
    `bigquery-public-data.census_bureau_usa.population_by_zip_2010` d
  JOIN
    `bigquery-public-data.utility_us.zipcode_area` e
  ON
    d.zipcode = e.zipcode
  GROUP BY
    state ) c
ON
  c.state = a.state_name
WHERE
  b.driver_distracted_by_name NOT IN ('Not Distracted', 'Unknown if Distracted', 'Not Reported')
GROUP BY
  state,
  population,
  c.state_pop
ORDER BY
  rate_per_100000 DESC
LIMIT 5
)
Database: nhtsa_traffic_fatalities (snowflake)
Question: I want to create a labeled dataset from the National Highway Traffic Safety Administration traffic fatality data that predicts whether a traffic accident involving more than one distinct person results in more than one fatality, where the label is 1 if an accident has more than one person with an injury severity code of 4 (fatal injury) and 0 otherwise. For each accident, include the numeric predictors: state_number, the vehicle body_type, the number_of_drunk_drivers, the day_of_week, the hour_of_crash, and a binary indicator for whether the accident occurred in a work zone (1 if it is not “None,” otherwise 0). Also, engineer a feature for the average absolute difference between travel_speed and speed_limit per accident, only considering travel speeds up to 151 mph (excluding codes 997, 998, 999) and speed limits up to 80 mph (excluding codes 98, 99), and categorize this average speed difference into levels from 0 to 4 in 20 mph increments with lower bounds inclusive and upper bounds exclusive. Finally, only include accidents that involve more than one distinct person.
SQL:
Database: nhtsa_traffic_fatalities (snowflake)
Question: Which top 3 states had the largest differences in the number of traffic accidents between rainy and clear weather during weekends in 2016? Please also provide the respective differences for each state.
SQL:
WITH weekend_accidents AS (
    SELECT
        state_name,
        CASE
            WHEN atmospheric_conditions_1_name = 'Rain' THEN 'Rain'
            WHEN atmospheric_conditions_1_name = 'Clear' THEN 'Clear'
            ELSE 'Other'
        END AS Weather_Condition,
        COUNT(DISTINCT consecutive_number) AS num_accidents
    FROM
        `bigquery-public-data.nhtsa_traffic_fatalities.accident_2016`
    WHERE
        EXTRACT(DAYOFWEEK FROM timestamp_of_crash) IN (1, 7)  -- 1 = Sunday, 7 = Saturday
        AND atmospheric_conditions_1_name IN ('Rain', 'Clear')
    GROUP BY
        state_name, Weather_Condition
),

weather_difference AS (
    SELECT
        state_name,
        MAX(CASE WHEN Weather_Condition = 'Rain' THEN num_accidents ELSE 0 END) AS Rain_Accidents,
        MAX(CASE WHEN Weather_Condition = 'Clear' THEN num_accidents ELSE 0 END) AS Clear_Accidents,
        ABS(MAX(CASE WHEN Weather_Condition = 'Rain' THEN num_accidents ELSE 0 END) -
            MAX(CASE WHEN Weather_Condition = 'Clear' THEN num_accidents ELSE 0 END)) AS Difference
    FROM
        weekend_accidents
    GROUP BY
        state_name
)

SELECT
    state_name,
    Difference
FROM
    weather_difference
ORDER BY
    Difference DESC
LIMIT 3;
Database: sdoh (snowflake)
Question: What is the increasing amount of the average earnings per job between the years 2012 and 2017 for each geographic region in Massachusetts (indicated by "MA" at the end of GeoName)?
SQL:
WITH bea_2012 AS (
  SELECT GeoFIPS, GeoName, Earnings_per_job_avg AS earnings_2012
  FROM `bigquery-public-data.sdoh_bea_cainc30.fips`
  WHERE Year='2012-01-01' AND ENDS_WITH(GeoName, "MA") IS TRUE
),

bea_2017 AS (
  SELECT GeoFIPS, GeoName, Earnings_per_job_avg AS earnings_2017
  FROM `bigquery-public-data.sdoh_bea_cainc30.fips`
  WHERE Year='2017-01-01' AND ENDS_WITH(GeoName, "MA") IS TRUE
),

earnings_diff AS (
  SELECT
    bea_2017.GeoFIPS, bea_2017.GeoName, bea_2017.earnings_2017, bea_2012.earnings_2012, 
    (bea_2017.earnings_2017 - bea_2012.earnings_2012) AS earnings_change
   FROM bea_2017 
   JOIN bea_2012
   ON bea_2017.GeoFIPS = bea_2012.GeoFIPS
)
 
SELECT * FROM earnings_diff WHERE earnings_change IS NOT NULL ORDER BY earnings_change DESC
Database: sdoh (snowflake)
Question: Identify the top 10 regions (counties) with the highest total number of SNAP-participating households, using the 2017 5-year ACS county-level data and SNAP enrollment data from January 1, 2017, excluding regions where the total SNAP participation is zero. For each of these regions, calculate the ratio of households earning under $20,000 to the total number of SNAP-participating households.
SQL:
WITH acs_2017 AS (
  SELECT geo_id, income_less_10000 AS i10, income_10000_14999 AS i15, income_15000_19999 AS i20
  FROM `bigquery-public-data.census_bureau_acs.county_2017_5yr`
 ),

snap_2017_Jan AS (
  SELECT FIPS, SNAP_All_Participation_Households AS snap_total
  FROM `bigquery-public-data.sdoh_snap_enrollment.snap_enrollment`
  WHERE Date = '2017-01-01'
)

SELECT acs_2017.geo_id, snap_2017_Jan.snap_total,
(acs_2017.i10 + acs_2017.i15 + acs_2017.i20) As households_under_20,
(acs_2017.i10 + acs_2017.i15 + acs_2017.i20)/snap_2017_Jan.snap_total As under_20_snap_ratio 
FROM acs_2017
JOIN snap_2017_Jan
ON  acs_2017.geo_id = snap_2017_Jan.FIPS
WHERE snap_2017_Jan.snap_total > 0
ORDER BY snap_2017_Jan.snap_total DESC
LIMIT 10
Database: sdoh (snowflake)
Question: What is the change in the number of homeless veterans between 2012 and 2018 for each CoC region in New York that has data available in both years?
SQL:
WITH homeless_2012 AS (
  SELECT Homeless_Veterans AS Vet12, CoC_Name  
  FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc` 
  WHERE SUBSTR(CoC_Number,0,2) = "NY" AND Count_Year = 2012
),
 
homeless_2018 AS (
  SELECT Homeless_Veterans AS Vet18, CoC_Name  
  FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc` 
  WHERE SUBSTR(CoC_Number,0,2) = "NY" AND Count_Year = 2018
),
 
veterans_change AS (
  SELECT homeless_2012.COC_Name, Vet12, Vet18, Vet18 - Vet12 AS VetChange
  FROM homeless_2018
  JOIN homeless_2012
  ON homeless_2018.CoC_Name = homeless_2012.CoC_Name
)

SELECT COC_Name, VetChange FROM veterans_change
ORDER BY CoC_Name;
Database: sdoh (snowflake)
Question: Calculate the percentage change in the total number of unsheltered homeless people from 2015 to 2018 for each state by summing the counts over all Continuums of Care (CoCs) within each state. Then, determine the national average of these state percentage changes. Identify the five states whose percentage change is closest to this national average percentage change. Please provide the state abbreviations.
SQL:
WITH homeless_2015 AS (
  SELECT Unsheltered_Homeless AS U15, SUBSTR(CoC_Number, 0, 2) as State_Abbr
  FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc`
  WHERE Count_Year = 2015
),
 
homeless_2018 AS (
  SELECT Unsheltered_Homeless AS U18, SUBSTR(CoC_Number, 0, 2) as State_Abbr
  FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc`
  WHERE Count_Year = 2018
),

unsheltered_change AS (
  SELECT homeless_2018.State_Abbr, 
         SUM(U15) AS Unsheltered_2015, 
         SUM(U18) AS Unsheltered_2018, 
         (SUM(U18) - SUM(U15)) / SUM(U15) * 100 AS Percent_Change
  FROM homeless_2018
  JOIN homeless_2015
  ON homeless_2018.State_Abbr = homeless_2015.State_Abbr
  GROUP BY State_Abbr
),

average_change AS (
  SELECT AVG(Percent_Change) AS Avg_Change
  FROM unsheltered_change
),

closest_to_avg AS (
  SELECT State_Abbr
  FROM unsheltered_change, average_change
  ORDER BY ABS(Percent_Change - Avg_Change)
  LIMIT 5
)

SELECT State_Abbr FROM closest_to_avg;
Database: sdoh (snowflake)
Question: Please list the average number of prenatal weeks in 2018 for counties in Wisconsin where more than 5% of the employed population had commutes of 45-59 minutes in 2017.
SQL:
WITH natality_2018 AS (
  SELECT County_of_Residence_FIPS AS FIPS, Ave_Number_of_Prenatal_Wks AS Vist_Ave, County_of_Residence
  FROM `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality` 
  WHERE SUBSTR(County_of_Residence_FIPS, 0, 2) = "55" AND Year = '2018-01-01'
),

acs_2017 AS (
  SELECT geo_id, commute_45_59_mins, employed_pop
  FROM `bigquery-public-data.census_bureau_acs.county_2017_5yr`
),

corr_tbl AS (
  SELECT
    n.County_of_Residence,
    ROUND((a.commute_45_59_mins / a.employed_pop) * 100, 2) AS percent_high_travel,
    n.Vist_Ave
  FROM acs_2017 a
  JOIN natality_2018 n
  ON a.geo_id = n.FIPS
)

SELECT County_of_Residence, Vist_Ave
FROM corr_tbl
WHERE percent_high_travel > 5
Database: sdoh (snowflake)
Question: Count the number of counties that experienced an increase in unemployment from 2015 to 2018, using 5-year ACS data, and a decrease in dual-eligible enrollee counts between December 1, 2015, and December 1, 2018.
SQL:
WITH acs_2018 AS (
  SELECT geo_id, unemployed_pop AS unemployed_2018  
  FROM `bigquery-public-data.census_bureau_acs.county_2018_5yr` 
),
 
acs_2015 AS (
  SELECT geo_id, unemployed_pop AS unemployed_2015  
  FROM `bigquery-public-data.census_bureau_acs.county_2015_5yr` 
),
 
unemployed_change AS (
  SELECT
    u18.unemployed_2018, u18.geo_id, u15.unemployed_2015,
    (u18.unemployed_2018 - u15.unemployed_2015) AS u_change
  FROM acs_2018 u18
  JOIN acs_2015 u15
  ON u18.geo_id = u15.geo_id
),
 
duals_Jan_2018 AS (
  SELECT Public_Total AS duals_2018, County_Name, FIPS 
  FROM `bigquery-public-data.sdoh_cms_dual_eligible_enrollment.dual_eligible_enrollment_by_county_and_program` 
  WHERE Date = '2018-12-01'
),

duals_Jan_2015 AS (
  SELECT Public_Total AS duals_2015, County_Name, FIPS
  FROM `bigquery-public-data.sdoh_cms_dual_eligible_enrollment.dual_eligible_enrollment_by_county_and_program` 
  WHERE Date = '2015-12-01'
),

duals_change AS (
  SELECT
    d18.FIPS, d18.County_Name, d18.duals_2018, d15.duals_2015,
    (d18.duals_2018 - d15.duals_2015) AS total_duals_diff
  FROM duals_Jan_2018 d18
  JOIN duals_Jan_2015 d15
  ON d18.FIPS = d15.FIPS
),
 
corr_tbl AS (
  SELECT unemployed_change.geo_id, duals_change.County_Name, unemployed_change.u_change, duals_change.total_duals_diff
  FROM unemployed_change
  JOIN duals_change
  ON unemployed_change.geo_id = duals_change.FIPS
)


SELECT COUNT(*)
FROM corr_tbl
WHERE
u_change >0
AND
corr_tbl.total_duals_diff < 0
Database: sdoh (snowflake)
Question: Could you assess the relationship between the poverty rates from the previous year's census data and the percentage of births without maternal morbidity for the years 2016 to 2018? Use only data for births where no maternal morbidity was reported and for each year, use the 5-year census data from the year before to compute the Pearson correlation coefficient
SQL:
WITH poverty_and_natality AS (
  SELECT
    EXTRACT(YEAR FROM n.Year) AS data_year,
    p.geo_id AS county_fips,
    (p.poverty / p.pop_determined_poverty_status) * 100 AS poverty_rate,
    SUM(n.Births) AS total_births,
    SUM(CASE WHEN n.Maternal_Morbidity_YN = 0 THEN n.Births ELSE 0 END) AS births_without_morbidity
  FROM
    `bigquery-public-data.census_bureau_acs.county_2015_5yr` p
  JOIN
    `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality_by_maternal_morbidity` n
  ON p.geo_id = n.County_of_Residence_FIPS
  WHERE
    p.pop_determined_poverty_status > 0 AND
    EXTRACT(YEAR FROM n.Year) = 2016
  GROUP BY
    p.geo_id, p.poverty, p.pop_determined_poverty_status, EXTRACT(YEAR FROM n.Year)
  UNION ALL
  SELECT
    EXTRACT(YEAR FROM n.Year) AS data_year,
    p.geo_id AS county_fips,
    (p.poverty / p.pop_determined_poverty_status) * 100 AS poverty_rate,
    SUM(n.Births) AS total_births,
    SUM(CASE WHEN n.Maternal_Morbidity_YN = 0 THEN n.Births ELSE 0 END) AS births_without_morbidity
  FROM
    `bigquery-public-data.census_bureau_acs.county_2016_5yr` p
  JOIN
    `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality_by_maternal_morbidity` n
  ON p.geo_id = n.County_of_Residence_FIPS
  WHERE
    p.pop_determined_poverty_status > 0 AND
    EXTRACT(YEAR FROM n.Year) = 2017
  GROUP BY
    p.geo_id, p.poverty, p.pop_determined_poverty_status, EXTRACT(YEAR FROM n.Year)
  UNION ALL
  SELECT
    EXTRACT(YEAR FROM n.Year) AS data_year,
    p.geo_id AS county_fips,
    (p.poverty / p.pop_determined_poverty_status) * 100 AS poverty_rate,
    SUM(n.Births) AS total_births,
    SUM(CASE WHEN n.Maternal_Morbidity_YN = 0 THEN n.Births ELSE 0 END) AS births_without_morbidity
  FROM
    `bigquery-public-data.census_bureau_acs.county_2017_5yr` p
  JOIN
    `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality_by_maternal_morbidity` n
  ON p.geo_id = n.County_of_Residence_FIPS
  WHERE
    p.pop_determined_poverty_status > 0 AND
    EXTRACT(YEAR FROM n.Year) = 2018
  GROUP BY
    p.geo_id, p.poverty, p.pop_determined_poverty_status, EXTRACT(YEAR FROM n.Year)
)

SELECT
  data_year,
  CORR(poverty_rate, (births_without_morbidity / total_births) * 100) AS correlation_coefficient
FROM
  poverty_and_natality
GROUP BY
  data_year
Database: openaq (snowflake)
Question: Which three cities have the largest difference between their 1990 EPA PM2.5 measurements (using units_of_measure = 'Micrograms/cubic meter (LC)' and parameter_name = 'Acceptable PM2.5 AQI & Speciation Mass') and their 2020 OpenAQ PM2.5 measurements (where pollutant = 'pm25' based on the year extracted from the timestamp), with both datasets matched by latitude and longitude rounded to two decimals, and the difference ordered from greatest to least?
SQL:
SELECT
  aq.city,
  epa.arithmetic_mean,
  aq.value,
  aq.timestamp,
  (epa.arithmetic_mean - aq.value)
FROM
  `bigquery-public-data.openaq.global_air_quality` AS aq
JOIN
  `bigquery-public-data.epa_historical_air_quality.air_quality_annual_summary` AS epa
ON
  ROUND(aq.latitude, 2) = ROUND(epa.latitude, 2)
  AND ROUND(aq.longitude, 2) = ROUND(epa.longitude, 2)
WHERE
  epa.units_of_measure = "Micrograms/cubic meter (LC)"
  AND epa.parameter_name = "Acceptable PM2.5 AQI & Speciation Mass"
  AND epa.year = 1990
  AND aq.pollutant = "pm25"
  AND EXTRACT(YEAR FROM aq.timestamp) = 2020
ORDER BY
  (epa.arithmetic_mean - aq.value) DESC
LIMIT 3
Database: stackoverflow (snowflake)
Question: Compute the monthly statistics for new StackOverflow users created in 2021. For each month, report the total number of new users, the percentage of these new users who asked at least one question within 30 days of signing up, and among those who asked a question within 30 days, the percentage who then answered at least one question after their first question and within 30 days following their first question.
SQL:
Database: STACKOVERFLOW (snowflake)
Question: How do the average reputation and number of badges vary among Stack Overflow users based on the number of complete years they have been members, considering only those who joined on or before October 1, 2021?
SQL:
WITH sub AS (
  SELECT 
    "users"."id",
    CAST(TO_TIMESTAMP(MAX("users"."creation_date") / 1000000.0) AS DATE) AS "user_creation_date",  -- 使用 MAX 聚合 creation_date 并转换为 DATE
    MAX("users"."reputation") AS "reputation",  
    SUM(CASE WHEN badges."user_id" IS NULL THEN 0 ELSE 1 END) AS "num_badges"
  FROM "STACKOVERFLOW"."STACKOVERFLOW"."USERS" "users"
  LEFT JOIN "STACKOVERFLOW"."STACKOVERFLOW"."BADGES" badges
    ON "users"."id" = badges."user_id"
  WHERE CAST(TO_TIMESTAMP("users"."creation_date" / 1000000.0) AS DATE) <= DATE '2021-10-01'
  GROUP BY "users"."id"
)

SELECT 
  DATEDIFF(YEAR, "user_creation_date", DATE '2021-10-01') AS "user_tenure",
  COUNT(1) AS "Num_Users",
  AVG("reputation") AS "Avg_Reputation",
  AVG("num_badges") AS "Avg_Num_Badges"
FROM sub
GROUP BY "user_tenure"
ORDER BY "user_tenure";
Database: stackoverflow (snowflake)
Question: You need to determine which day of the week has the third highest percentage of questions on Stack Overflow that receive an answer within an hour. To do this, use the question creation date from the posts_questions table and the earliest answer creation date from the posts_answers table. Once you’ve calculated the percentage of questions that get answered within an hour for each day, identify the day with the third highest percentage and report that percentage.
SQL:
WITH first_answers AS (
  SELECT
    parent_id AS question_id,
    MIN(creation_date) AS first_answer_date
  FROM
    `bigquery-public-data.stackoverflow.posts_answers`
  GROUP BY
    parent_id
)

SELECT
  FORMAT_DATE('%A', DATE(q.creation_date)) AS question_day,
  SUM(CASE WHEN f.first_answer_date IS NOT NULL AND TIMESTAMP_DIFF(f.first_answer_date, q.creation_date, MINUTE) <= 60 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS percent_questions
FROM
  `bigquery-public-data.stackoverflow.posts_questions` q
LEFT JOIN
  first_answers f
ON
  q.id = f.question_id
GROUP BY
  question_day
ORDER BY
  percent_questions DESC
LIMIT 1 OFFSET 2
Database: stackoverflow (snowflake)
Question: Please provide the display name of the user who has answered the most questions on Stack Overflow, considering only users with a reputation greater than 10.
SQL:
WITH UserAnswers AS (
  SELECT
    owner_user_id AS answer_owner_id,
    COUNT(id) AS answer_count
  FROM bigquery-public-data.stackoverflow.posts_answers
  WHERE owner_user_id IS NOT NULL
  GROUP BY owner_user_id
),
DetailedUsers AS (
  SELECT
    id AS user_id,
    display_name AS user_display_name,
    reputation
  FROM bigquery-public-data.stackoverflow.users
  WHERE display_name IS NOT NULL AND reputation > 10
),
RankedUsers AS (
  SELECT
    u.user_display_name,
    u.reputation,
    a.answer_count,
    ROW_NUMBER() OVER (ORDER BY a.answer_count DESC) AS rank
  FROM DetailedUsers u
  JOIN UserAnswers a ON u.user_id = a.answer_owner_id
)
SELECT
  user_display_name,
FROM RankedUsers
WHERE rank = 1;
Database: stackoverflow (snowflake)
Question: What is the highest number of answers received for a single Python 2 specific question on Stack Overflow, excluding any discussions that involve Python 3?
SQL:
WITH
  python2_questions AS (
    SELECT
      q.id AS question_id,
      q.title,
      q.body AS question_body,
      q.tags
    FROM
      `bigquery-public-data.stackoverflow.posts_questions` q
    WHERE
      (LOWER(q.tags) LIKE '%python-2%'
      OR LOWER(q.tags) LIKE '%python-2.x%'
      OR (
        LOWER(q.title) LIKE '%python 2%'
        OR LOWER(q.body) LIKE '%python 2%'
        OR LOWER(q.title) LIKE '%python2%'
        OR LOWER(q.body) LIKE '%python2%'
      ))
      AND (
        LOWER(q.title) NOT LIKE '%python 3%'
        AND LOWER(q.body) NOT LIKE '%python 3%'
        AND LOWER(q.title) NOT LIKE '%python3%'
        AND LOWER(q.body) NOT LIKE '%python3%'
      )
  )

SELECT
  COUNT(*) AS count_number
FROM
  python2_questions q
LEFT JOIN
  `bigquery-public-data.stackoverflow.posts_answers` a
ON
  q.question_id = a.parent_id
GROUP BY q.question_id
ORDER BY count_number DESC
LIMIT 1