nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: CENSUS_BUREAU_ACS_2 (snowflake)
Question: Which are the top five states with the greatest average difference in median income between 2015 and 2018 at the ZIP code level, and what is the corresponding average number of vulnerable employees across wholesale trade, natural resources and construction, arts and entertainment, information, and retail trade industries in 2017 according to the ACS Five-Year Estimates and ZIP code boundaries data?
SQL:
WITH median_income_diff_by_zipcode AS (
  WITH acs_2018 AS (
    SELECT
      "geo_id",
      "median_income" AS "median_income_2018"
    FROM
      CENSUS_BUREAU_ACS_2.CENSUS_BUREAU_ACS."ZIP_CODES_2018_5YR"
  ),
  acs_2015 AS (
    SELECT
      "geo_id",
      "median_income" AS "median_income_2015"
    FROM
      CENSUS_BUREAU_ACS_2.CENSUS_BUREAU_ACS."ZIP_CODES_2015_5YR"
  ),
  acs_diff AS (
    SELECT
      a18."geo_id",
      (a18."median_income_2018" - a15."median_income_2015") AS "median_income_diff"
    FROM
      acs_2018 a18
    JOIN
      acs_2015 a15 ON a18."geo_id" = a15."geo_id"
  )
  SELECT
    "geo_id",
    AVG("median_income_diff") AS "avg_median_income_diff"
  FROM
    acs_diff
  WHERE
    "median_income_diff" IS NOT NULL
  GROUP BY "geo_id"
),
base_census AS (
  SELECT
    geo."state_name",
    AVG(i."avg_median_income_diff") AS "avg_median_income_diff",
    AVG(
      "employed_wholesale_trade" * 0.38423645320197042 +
      "occupation_natural_resources_construction_maintenance" * 0.48071410777129553 +
      "employed_arts_entertainment_recreation_accommodation_food" * 0.89455676291236841 +
      "employed_information" * 0.31315240083507306 +
      "employed_retail_trade" * 0.51
    ) AS "avg_vulnerable"
  FROM
    CENSUS_BUREAU_ACS_2.CENSUS_BUREAU_ACS."ZIP_CODES_2017_5YR" AS census
  JOIN
    median_income_diff_by_zipcode i ON CAST(census."geo_id" AS STRING) = i."geo_id"
  JOIN
    CENSUS_BUREAU_ACS_2.GEO_US_BOUNDARIES."ZIP_CODES" geo ON census."geo_id" = geo."zip_code"
  GROUP BY geo."state_name"
)

SELECT 
  "state_name",
  "avg_median_income_diff",
  "avg_vulnerable"
FROM 
  base_census
ORDER BY 
  "avg_median_income_diff" DESC
LIMIT 5;
Database: CENSUS_BUREAU_ACS_2 (snowflake)
Question: Using data on ZIP-level median income differences between 2015 and 2018, along with the 2017 ACS employment figures, list each state in descending order of total vulnerable workers, where “vulnerable” is defined as 38% of wholesale trade employees and 41% of manufacturing employees in 2017. Your results should include the state name, the number of vulnerable wholesale trade workers, the number of vulnerable manufacturing workers, and the combined total of these vulnerable workers.
SQL:
Database: CENSUS_BUREAU_ACS_2 (snowflake)
Question: Find the top 3 states with the smallest adjusted non-labor force population using 2017 ACS tract-level data. Calculate the adjusted non-labor force population as (unemployed_pop + not_in_labor_force - group_quarters), clamping any negative values to zero. For each of these states, display the state abbreviation, the total median income change between 2015 and 2018 across all tracts, the total adjusted non-labor force population, and the average population-adjusted proportion (calculated as the ratio of adjusted non-labor force to total population at the tract level). Join tract data to states using FIPS code prefixes, exclude any tracts with null income differences, and sort results by the adjusted non-labor force population in ascending order.
SQL:
Database: GEO_OPENSTREETMAP (snowflake)
Question: Within the rectangular area defined by the geogpoints (31.1798246, 18.4519921), (54.3798246, 18.4519921), (54.3798246, 33.6519921), and (31.1798246, 33.6519921), which are the top three usernames responsible for the highest number of historical nodes, originally tagged with the amenities ‘hospital’, ‘clinic’, or ‘doctors’, that do not appear anymore in the current planet_nodes dataset?
SQL:
Database: GEO_OPENSTREETMAP (snowflake)
Question: Find the name of the OpenStreetMap relation that encompasses the most features within the same geographic area as the multipolygon tagged with the Wikidata item 'Q1095'. The relation should have a specified name and no 'wikidata' tag, and at least one of its included features must have a 'wikidata' tag. The analysis should be conducted using the planet_features table. Return the name of this relation.
SQL:
Database: GEO_OPENSTREETMAP (snowflake)
Question: Among all multipolygons located within the same geographic area as the multipolygon associated with Wikidata item Q191, but lacking a 'wikidata' tag themselves, which two rank highest by the number of points that lie within their boundaries, and what are their names?
SQL:
WITH bounding_area AS (
    SELECT "geometry" AS geometry
    FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_FEATURES,
    LATERAL FLATTEN(INPUT => "all_tags") AS tag
    WHERE "feature_type" = 'multipolygons'
      AND tag.value:"key" = 'wikidata'
      AND tag.value:"value" = 'Q191'
),
bounding_area_features AS (
    SELECT 
        planet_features."osm_id", 
        planet_features."feature_type", 
        planet_features."geometry", 
        planet_features."all_tags"
    FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_FEATURES AS planet_features,
         bounding_area
    WHERE ST_DWITHIN(
        ST_GEOGFROMWKB(planet_features."geometry"), 
        ST_GEOGFROMWKB(bounding_area.geometry), 
        0.0
    )
),
osm_id_with_wikidata AS (
    SELECT DISTINCT
        baf."osm_id"
    FROM bounding_area_features AS baf,
         LATERAL FLATTEN(INPUT => baf."all_tags") AS tag
    WHERE tag.value:"key" = 'wikidata'
),

polygons_wo_wikidata AS (
    SELECT 
        baf."osm_id",
        tag.value:"value" as name,
        baf."geometry" as geometry
    FROM bounding_area_features AS baf
    LEFT JOIN osm_id_with_wikidata AS wd
      ON baf."osm_id" = wd."osm_id",
    LATERAL FLATTEN(INPUT => "all_tags") AS tag
    WHERE wd."osm_id" IS NULL
    AND baf."osm_id" IS NOT NULL
    AND baf."feature_type" = 'multipolygons'
    AND tag.value:"key" = 'name'
)

SELECT 
    TRIM(pww.name) as name
FROM bounding_area_features AS baf
JOIN polygons_wo_wikidata AS pww
    ON ST_DWITHIN(
        ST_GEOGFROMWKB(baf."geometry"), 
        ST_GEOGFROMWKB(pww.geometry), 
        0.0
    )
LEFT JOIN osm_id_with_wikidata AS wd
    ON baf."osm_id" = wd."osm_id"
WHERE wd."osm_id" IS NOT NULL
  AND baf."feature_type" = 'points'
GROUP BY pww.name
ORDER BY COUNT(baf."osm_id") DESC
LIMIT 2
Database: GEO_OPENSTREETMAP_CENSUS_PLACES (snowflake)
Question: Can you find the shortest distance between any two amenities (either a library, place of worship, or community center) located within Philadelphia, analyzed through pennsylvania table and planet features points?
SQL:
WITH philadelphia AS (
    SELECT 
        * 
    FROM 
        GEO_OPENSTREETMAP_CENSUS_PLACES.GEO_US_CENSUS_PLACES.PLACES_PENNSYLVANIA
    WHERE 
        "place_name" = 'Philadelphia'
),
amenities AS (
    SELECT 
        features.*, 
        tags.value:"value" AS amenity
    FROM 
        GEO_OPENSTREETMAP_CENSUS_PLACES.GEO_OPENSTREETMAP.PLANET_FEATURES_POINTS AS features
    CROSS JOIN philadelphia
    -- Use FLATTEN on "all_tags" to get the tags and filter by "key"
    , LATERAL FLATTEN(input => features."all_tags") AS tags
    WHERE 
        ST_CONTAINS(ST_GEOGFROMWKB(philadelphia."place_geom"), ST_GEOGFROMWKB(features."geometry"))
    AND 
        tags.value:"key" = 'amenity' 
    AND 
        tags.value:"value" IN ('library', 'place_of_worship', 'community_centre')
),
joiin AS (
    SELECT 
        a1.*, 
        a2."osm_id" AS nearest_osm_id, 
        ST_DISTANCE(ST_GEOGFROMWKB(a1."geometry"), ST_GEOGFROMWKB(a2."geometry")) AS distance, 
        ROW_NUMBER() OVER (PARTITION BY a1."osm_id" ORDER BY ST_DISTANCE(ST_GEOGFROMWKB(a1."geometry"), ST_GEOGFROMWKB(a2."geometry"))) AS row_num
    FROM amenities a1
    CROSS JOIN amenities a2
    WHERE a1."osm_id" < a2."osm_id"
    ORDER BY a1."osm_id", distance
) 
SELECT distance
FROM joiin  
WHERE row_num = 1
ORDER BY distance ASC
LIMIT 1;
Database: GEO_OPENSTREETMAP_WORLDPOP (snowflake)
Question: Based on the most recent 1km population grid data in Singapore before January 2023, using ST_CONVEXHULL to aggregate all population grid centroids into a bounding region and ST_INTERSECTS to identify hospitals from OpenStreetMap’s planet layer (layer_code in (2110, 2120)) that fall within this region, then calculating the distance from each grid cell to its nearest hospital, what is the total population of the grid cell that is farthest from any hospital?
SQL:
WITH country_name AS (
  SELECT 'Singapore' AS value
),

last_updated AS (
  SELECT
    MAX("last_updated") AS value
  FROM GEO_OPENSTREETMAP_WORLDPOP.WORLDPOP.POPULATION_GRID_1KM AS pop
    INNER JOIN country_name ON (pop."country_name" = country_name.value)
  WHERE "last_updated" < '2023-01-01'
),

aggregated_population AS (
  SELECT
    "geo_id",
    SUM("population") AS sum_population,
    ST_POINT("longitude_centroid", "latitude_centroid") AS centr  -- 计算每个 geo_id 的中心点
  FROM
    GEO_OPENSTREETMAP_WORLDPOP.WORLDPOP.POPULATION_GRID_1KM AS pop
    INNER JOIN country_name ON (pop."country_name" = country_name.value)
    INNER JOIN last_updated ON (pop."last_updated" = last_updated.value)
  GROUP BY "geo_id", "longitude_centroid", "latitude_centroid"
),

population AS (
  SELECT
    SUM(sum_population) AS sum_population,
    ST_ENVELOPE(ST_UNION_AGG(centr)) AS boundingbox  -- 使用 ST_ENVELOPE 来代替 ST_CONVEXHULL
  FROM aggregated_population
),

hospitals AS (
  SELECT
    layer."geometry"
  FROM
    GEO_OPENSTREETMAP_WORLDPOP.GEO_OPENSTREETMAP.PLANET_LAYERS AS layer
    INNER JOIN population ON ST_INTERSECTS(population.boundingbox, ST_GEOGFROMWKB(layer."geometry"))
  WHERE
    layer."layer_code" IN (2110, 2120)
),

distances AS (
  SELECT
    pop."geo_id",
    pop."population",
    MIN(ST_DISTANCE(ST_GEOGFROMWKB(pop."geog"), ST_GEOGFROMWKB(hospitals."geometry"))) AS distance
  FROM
    GEO_OPENSTREETMAP_WORLDPOP.WORLDPOP.POPULATION_GRID_1KM AS pop
    INNER JOIN country_name ON pop."country_name" = country_name.value
    INNER JOIN last_updated ON pop."last_updated" = last_updated.value
    CROSS JOIN hospitals
  WHERE pop."population" > 0
  GROUP BY "geo_id", "population"
)

SELECT
  SUM(pd."population") AS population
FROM
  distances pd
CROSS JOIN population p
GROUP BY distance
ORDER BY distance DESC
LIMIT 1;
Database: CRYPTO (snowflake)
Question: Can you calculate the daily change in the market value of USDC tokens (address `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48`) for 2023, based on Ethereum transactions? The change should be computed from minting (input pattern `0x40c10f19%`) and burning (input pattern `0x42966c68%`) operations. For each transaction, minting should be positive and burning negative. Extract the relevant amount from the 'input' field as a hexadecimal, convert it to millions, express it in USD format. Group the results by date and order them in descending order.
SQL:
SELECT 
  TO_DATE(TO_TIMESTAMP_NTZ("block_timestamp" / 1000000)) AS "Date",  -- 将时间戳转换为日期格式，除以1000000
  TO_CHAR(SUM(
      CASE
          WHEN "input" LIKE '0x40c10f19%' THEN 1
          ELSE -1
      END * 
      CAST(CONCAT('0x', LTRIM(SUBSTRING("input", 
                                       CASE 
                                           WHEN "input" LIKE '0x40c10f19%' THEN 75
                                           ELSE 11
                                       END, 64), '0')) AS FLOAT) / 1000000)
  , '$999,999,999,999') AS "Δ Total Market Value"
FROM 
  "CRYPTO"."CRYPTO_ETHEREUM"."TRANSACTIONS"
WHERE 
  TO_DATE(TO_TIMESTAMP_NTZ("block_timestamp" / 1000000)) BETWEEN '2023-01-01' AND '2023-12-31'
  AND "to_address" = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'  -- USDC Token
  AND ("input" LIKE '0x42966c68%' -- Burn
       OR "input" LIKE '0x40c10f19%' -- Mint
  )
GROUP BY 
  TO_DATE(TO_TIMESTAMP_NTZ("block_timestamp" / 1000000))
ORDER BY 
  "Date" DESC;
Database: CRYPTO (snowflake)
Question: Using only the traces, can you calculate daily cumulative counts of smart contracts created by external addresses (where the trace_address is NULL) versus those created by other contracts (where the trace_address is NOT NULL) for each date from 2017-01-01 through 2021-12-31, ensuring that all dates in this range are included even if no new contracts were created on some days, and showing monotonically increasing cumulative totals for both categories?
SQL:
Database: CRYPTO (snowflake)
Question: Determine the final Ether balance of the Ethereum address that initiated the highest number of successful transactions prior to September 1, 2021 (UTC), excluding calls of type delegatecall, callcode, or staticcall and including all relevant incoming and outgoing transfers, miner rewards, and gas fee deductions, with the final balance presented in Ether after converting from the native unit.
SQL:
Database: CRYPTO (snowflake)
Question: Using only the Ethereum traces table, can you provide a daily cumulative count of smart contracts created by external users (where trace_address is null) versus contracts created by other contracts (where trace_address is not null) between August 30, 2018, and September 30, 2018? Ensure results include every date in this range, even if no new contracts were created, and show strictly increasing cumulative totals.
SQL:
Database: CRYPTO (snowflake)
Question: What is the difference between the average hourly changes in transaction values for the Ethereum token 0x68e54af74b22acaccffa04ccaad13be16ed14eac, specifically considering only transactions where the address 0x8babf0ba311aab914c00e8fda7e8558a8b66de5d was the sender or the address 0xfbd6c6b112214d949dcdfb1217153bc0a742862f was the receiver, between January 1, 2019, and December 31, 2020, when comparing 2019 to 2020?
SQL:
Database: CRYPTO (snowflake)
Question: Which Ethereum address has the top 3 smallest positive balance from transactions involving the token at address "0xa92a861fc11b99b24296af880011b47f9cafb5ab"?
SQL:
WITH transaction_addresses AS (
    SELECT 
        "from_address", 
        "to_address", 
        CAST("value" AS NUMERIC) / 1000000 AS "value"
    FROM 
        "CRYPTO"."CRYPTO_ETHEREUM"."TOKEN_TRANSFERS"
    WHERE 
        "token_address" = '0xa92a861fc11b99b24296af880011b47f9cafb5ab'
),

out_addresses AS (
    SELECT 
        "from_address", 
        SUM(-1 * "value") AS "total_value"
    FROM 
        transaction_addresses
    GROUP BY 
        "from_address"
),

in_addresses AS (
    SELECT 
        "to_address", 
        SUM("value") AS "total_value"
    FROM 
        transaction_addresses
    GROUP BY 
        "to_address"
),

all_addresses AS (
    SELECT 
        "from_address" AS "address", 
        "total_value"
    FROM 
        out_addresses

    UNION ALL

    SELECT 
        "to_address" AS "address", 
        "total_value"
    FROM 
        in_addresses
)

SELECT 
    "address"
FROM 
    all_addresses
GROUP BY 
    "address"
HAVING 
    SUM("total_value") > 0
ORDER BY 
    SUM("total_value") ASC
LIMIT 3;
Database: CRYPTO (snowflake)
Question: Can you pull the blockchain timestamp, block number, and transaction hash for the first five mint and burn events from Ethereum logs for the address '0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8'? Please include mint events identified by the topic '0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde' and burn events by '0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c', and order them by block timestamp from the oldest to the newest.
SQL:
WITH parsed_burn_logs AS (
  SELECT
    logs."block_timestamp" AS block_timestamp,
    logs."block_number" AS block_number,
    logs."transaction_hash" AS transaction_hash,
    logs."log_index" AS log_index,
    PARSE_JSON(logs."data") AS data,
    logs."topics"
  FROM CRYPTO.CRYPTO_ETHEREUM.LOGS AS logs
  WHERE logs."address" = '0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8'
    AND logs."topics"[0] = '0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c'
),
parsed_mint_logs AS (
  SELECT
    logs."block_timestamp" AS block_timestamp,
    logs."block_number" AS block_number,
    logs."transaction_hash" AS transaction_hash,
    logs."log_index" AS log_index,
    PARSE_JSON(logs."data") AS data,
    logs."topics"
  FROM CRYPTO.CRYPTO_ETHEREUM.LOGS AS logs
  WHERE logs."address" = '0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8'
    AND logs."topics"[0] = '0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde'
)

SELECT
    block_timestamp,
    block_number,
    transaction_hash
FROM parsed_mint_logs

UNION ALL

SELECT
    block_timestamp,
    block_number,
    transaction_hash
FROM parsed_burn_logs

ORDER BY block_timestamp
LIMIT 5;
Database: CRYPTO (snowflake)
Question: Which six Ethereum addresses, excluding '0x0000000000000000000000000000000000000000', have the largest absolute differences between their previous and current balances from the tokens at addresses '0x0d8775f648430679a709e98d2b0cb6250d2887ef0' and '0x1e15c05cbad367f044cbfbafda3d9a1510db5513'?
SQL:
Database: CRYPTO (snowflake)
Question: Calculate the annual differences in Bitcoin output value averages between two methods: Merged input/output records: Combine the inputs and outputs tables, filter to only output records, and calculate yearly averages. Transactions table: Directly use the output_value field from the transactions table for yearly averages. Show the difference (merged outputs average minus transactions average) only for years with data in both methods.
SQL:
WITH all_transactions AS (
    SELECT 
        TO_TIMESTAMP_NTZ("block_timestamp" / 1000000) AS "timestamp",  -- 将时间戳转换为日期时间格式
        "value",
        'input' AS "type"
    FROM 
        "CRYPTO"."CRYPTO_BITCOIN"."INPUTS"
    UNION ALL
    SELECT 
        TO_TIMESTAMP_NTZ("block_timestamp" / 1000000) AS "timestamp",  -- 将时间戳转换为日期时间格式
        "value",
        'output' AS "type"
    FROM 
        "CRYPTO"."CRYPTO_BITCOIN"."OUTPUTS"
),
filtered_transactions AS (
    SELECT
        EXTRACT(YEAR FROM "timestamp") AS "year",
        "value"
    FROM 
        all_transactions
    WHERE "type" = 'output'
),
average_output_values AS (
    SELECT
        "year",
        AVG("value") AS "avg_value"
    FROM 
        filtered_transactions
    GROUP BY "year"
),
average_transaction_values AS (
    SELECT 
        EXTRACT(YEAR FROM TO_TIMESTAMP_NTZ("block_timestamp" / 1000000)) AS "year",  -- 同样转换时间戳
        AVG("output_value") AS "avg_transaction_value" 
    FROM 
        "CRYPTO"."CRYPTO_BITCOIN"."TRANSACTIONS" 
    GROUP BY "year" 
    ORDER BY "year"
),
common_years AS (
    SELECT
        ao."year",
        ao."avg_value" AS "avg_output_value",
        atv."avg_transaction_value"
    FROM
        average_output_values ao
    JOIN
        average_transaction_values atv 
        ON ao."year" = atv."year"
)

SELECT
    "year",
    "avg_transaction_value" - "avg_output_value" AS "difference"
FROM
    common_years
ORDER BY
    "year";
Database: CRYPTO (snowflake)
Question: Using double-entry bookkeeping principles by treating transaction inputs as debits (negative values) and outputs as credits (positive values) for all Bitcoin Cash transactions between 2014-03-01 and 2014-04-01, how can we calculate the maximum and minimum final balances grouped by address type from these transactions?
SQL:
WITH double_entry_book AS (
    -- debits
    SELECT
        ARRAY_TO_STRING("inputs".value:addresses, ',') AS "address",  -- Use the correct JSON path notation
        "inputs".value:type AS "type",
        - "inputs".value:value AS "value"
    FROM CRYPTO.CRYPTO_BITCOIN_CASH.TRANSACTIONS,
         LATERAL FLATTEN(INPUT => "inputs") AS "inputs"
    WHERE TO_TIMESTAMP("block_timestamp" / 1000000) >= '2014-03-01' 
      AND TO_TIMESTAMP("block_timestamp" / 1000000) < '2014-04-01'

    UNION ALL
 
    -- credits
    SELECT
        ARRAY_TO_STRING("outputs".value:addresses, ',') AS "address",  -- Use the correct JSON path notation
        "outputs".value:type AS "type",
        "outputs".value:value AS "value"
    FROM CRYPTO.CRYPTO_BITCOIN_CASH.TRANSACTIONS, 
         LATERAL FLATTEN(INPUT => "outputs") AS "outputs"
    WHERE TO_TIMESTAMP("block_timestamp" / 1000000) >= '2014-03-01' 
      AND TO_TIMESTAMP("block_timestamp" / 1000000) < '2014-04-01'
),
address_balances AS (
    SELECT 
        "address",
        "type",
        SUM("value") AS "balance"
    FROM double_entry_book
    GROUP BY "address", "type"
),
max_min_balances AS (
    SELECT
        "type",
        MAX("balance") AS max_balance,
        MIN("balance") AS min_balance
    FROM address_balances
    GROUP BY "type"
)
SELECT
    REPLACE("type", '"', '') AS "type",  -- Replace double quotes with nothing
    max_balance,
    min_balance
FROM max_min_balances
ORDER BY "type";
Database: CRYPTO (snowflake)
Question: In April 2023, what are the highest and lowest balances across all Dash addresses when calculating the net balance for each address using double-entry bookkeeping (where inputs are treated as debits/negative values and outputs as credits/positive values)? Consider all transactions filtered by block_timestamp_month='2023-04-01', and when an address appears as an array in the data, concatenate the array elements into a comma-separated string. For each address and type combination, sum all the values to determine the balance.
SQL:
Database: CRYPTO (snowflake)
Question: What were the maximum and minimum net balance changes for Ethereum Classic addresses on October 14, 2016? Calculate these by summing all transactions where addresses received funds (debits), sent funds (credits), and paid or received gas fees. Only include successful status transactions and exclude internal calls of types. For gas fees, consider both the fees paid by transaction senders and received by miners, calculated as multiplied by the gas price for both miners and senders
SQL:
WITH double_entry_book AS (
    -- Debits
    SELECT 
        "to_address" AS "address", 
        "value" AS "value"
    FROM 
        CRYPTO.CRYPTO_ETHEREUM_CLASSIC.TRACES
    WHERE 
        "to_address" IS NOT NULL
        AND "status" = 1
        AND ("call_type" NOT IN ('delegatecall', 'callcode', 'staticcall') OR "call_type" IS NULL)
        AND TO_DATE(TO_TIMESTAMP("block_timestamp" / 1000000)) = '2016-10-14'

    UNION ALL
    
    -- Credits
    SELECT 
        "from_address" AS "address", 
        - "value" AS "value"
    FROM 
        CRYPTO.CRYPTO_ETHEREUM_CLASSIC.TRACES
    WHERE 
        "from_address" IS NOT NULL
        AND "status" = 1
        AND ("call_type" NOT IN ('delegatecall', 'callcode', 'staticcall') OR "call_type" IS NULL)
        AND TO_DATE(TO_TIMESTAMP("block_timestamp" / 1000000)) = '2016-10-14'

    UNION ALL

    -- Transaction Fees Debits
    SELECT 
        "miner" AS "address", 
        SUM(CAST("receipt_gas_used" AS NUMERIC) * CAST("gas_price" AS NUMERIC)) AS "value"
    FROM 
        CRYPTO.CRYPTO_ETHEREUM_CLASSIC.TRANSACTIONS AS "transactions"
    JOIN 
        CRYPTO.CRYPTO_ETHEREUM_CLASSIC.BLOCKS AS "blocks" 
        ON "blocks"."number" = "transactions"."block_number"
    WHERE 
        TO_DATE(TO_TIMESTAMP("block_timestamp" / 1000000)) = '2016-10-14'
    GROUP BY 
        "blocks"."miner"

    UNION ALL
    
    -- Transaction Fees Credits
    SELECT 
        "from_address" AS "address", 
        -(CAST("receipt_gas_used" AS NUMERIC) * CAST("gas_price" AS NUMERIC)) AS "value"
    FROM 
        CRYPTO.CRYPTO_ETHEREUM_CLASSIC.TRANSACTIONS
    WHERE 
        TO_DATE(TO_TIMESTAMP("block_timestamp" / 1000000)) = '2016-10-14'
),
net_changes AS (
    SELECT 
        "address",
        SUM("value") AS "net_change"
    FROM 
        double_entry_book
    GROUP BY 
        "address"
)
SELECT 
    MAX("net_change") AS "max_net_change",
    MIN("net_change") AS "min_net_change"
FROM
    net_changes;
Database: CRYPTO (snowflake)
Question: Analyze Bitcoin transactions since July 2023 to determine monthly percentages of: (1)Transactions classified as CoinJoins (defined by >2 outputs, output value ≤ input value, and multiple identical-value outputs), (2) UTXOs involved in CoinJoins (calculated as the average of CoinJoin input/output ratios against total network UTXOs), (3) Transaction volume (based on input value) attributed to CoinJoins. Provide results in a table with monthly metrics for transactions, UTXOs, and volume.
SQL:
Database: CRYPTO (snowflake)
Question: Find all exactly 2-hop transaction paths on Zilliqa blockchain between the source address 'zil1jrpjd8pjuv50cfkfr7eu6yrm3rn5u8rulqhqpz' and destination address 'zil19nmxkh020jnequql9kvqkf3pkwm0j0spqtd26e', considering both regular transactions and contract transitions. A 2-hop path means there must be an intermediate address between source and destination. Exclude paths where any intermediate address has more than 50 outgoing transactions to filter out exchanges and high-activity wallets. Ensure transactions in each path follow chronological order (earlier transaction timestamps first). Display results in the format: '<source> --(tx ABCDE..)--> <intermediate> --(tx FGHIJ..)--> <destination>' where the transaction IDs are truncated to the first 5 characters. Include only confirmed on-chain transactions in both steps of the path.
SQL:
Database: CRYPTO (snowflake)
Question: From the oracle requests table, retrieve the 10 most recent oracle requests with script ID 3. For each request, extract all symbol-rate pairs by matching each symbol in the "symbols" array with its corresponding rate at the same position in the "rates" array from the decoded result. Adjust each rate by dividing it by the request's multiplier value. Return the block timestamp, oracle request ID, symbol, and the adjusted rate for each symbol-rate pair. Sort the results in chronological order with the newest records first.
SQL:
Database: HUMAN_GENOME_VARIANTS (snowflake)
Question: About the refined human genetic variations collected in phase 3 on 2015-02-20, I want to know the minimum and maximum start positions as well as the proportions of these two respectively for reference bases 'AT' and 'TA'.
SQL:
WITH A AS (
    SELECT
        "reference_bases",
        "start_position"
    FROM
        "HUMAN_GENOME_VARIANTS"."HUMAN_GENOME_VARIANTS"."_1000_GENOMES_PHASE_3_OPTIMIZED_SCHEMA_VARIANTS_20150220"
    WHERE
        "reference_bases" IN ('AT', 'TA')
),
B AS (
    SELECT
        "reference_bases",
        MIN("start_position") AS "min_start_position",
        MAX("start_position") AS "max_start_position",
        COUNT(1) AS "total_count"
    FROM
        A
    GROUP BY
        "reference_bases"
),
min_counts AS (
    SELECT
        A."reference_bases",  -- Explicitly referencing the column from table A
        A."start_position" AS "min_start_position",
        COUNT(1) AS "min_count"
    FROM
        A
    INNER JOIN B 
        ON A."reference_bases" = B."reference_bases"
    WHERE
        A."start_position" = B."min_start_position"
    GROUP BY
        A."reference_bases", A."start_position"
),
max_counts AS (
    SELECT
        A."reference_bases",  -- Explicitly referencing the column from table A
        A."start_position" AS "max_start_position",
        COUNT(1) AS "max_count"
    FROM
        A
    INNER JOIN B
        ON A."reference_bases" = B."reference_bases"
    WHERE
        A."start_position" = B."max_start_position"
    GROUP BY
        A."reference_bases", A."start_position"
)
SELECT
    B."reference_bases",  -- Explicitly referencing the column from table B
    B."min_start_position",
    CAST(min_counts."min_count" AS FLOAT) / B."total_count" AS "min_position_ratio",
    B."max_start_position",
    CAST(max_counts."max_count" AS FLOAT) / B."total_count" AS "max_position_ratio"
FROM
    B
LEFT JOIN
    min_counts ON B."reference_bases" = min_counts."reference_bases" AND B."min_start_position" = min_counts."min_start_position"
LEFT JOIN
    max_counts ON B."reference_bases" = max_counts."reference_bases" AND B."max_start_position" = max_counts."max_start_position"
ORDER BY
    B."reference_bases";
Database: ETHEREUM_BLOCKCHAIN (snowflake)
Question: Calculate the average balance (in quadrillions, 10^15) of the top 10 Ethereum addresses by net balance, including incoming and outgoing transfers from traces (only successful transactions and excluding call types like delegatecall, callcode, and staticcall), miner rewards (sum of gas fees per block), and sender gas fee deductions. Exclude null addresses and round the result to two decimal places.
SQL:
WITH double_entry_book AS (
  -- Debits
  SELECT 
    "to_address" AS "address",
    "value" AS "value"
  FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TRACES"
  WHERE "to_address" IS NOT NULL
    AND "status" = 1
    AND ("call_type" NOT IN ('delegatecall', 'callcode', 'staticcall') OR "call_type" IS NULL)
  
  UNION ALL
  
  -- Credits
  SELECT 
    "from_address" AS "address",
    - "value" AS "value"
  FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TRACES"
  WHERE "from_address" IS NOT NULL
    AND "status" = 1
    AND ("call_type" NOT IN ('delegatecall', 'callcode', 'staticcall') OR "call_type" IS NULL)
  
  UNION ALL
  
  -- Transaction fees debits
  SELECT 
    "miner" AS "address",
    SUM(CAST("receipt_gas_used" AS NUMBER) * CAST("gas_price" AS NUMBER)) AS "value"
  FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TRANSACTIONS" AS "transactions"
  JOIN "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."BLOCKS" AS "blocks"
    ON "blocks"."number" = "transactions"."block_number"
  GROUP BY "blocks"."miner"
  
  UNION ALL
  
  -- Transaction fees credits
  SELECT 
    "from_address" AS "address",
    -(CAST("receipt_gas_used" AS NUMBER) * CAST("gas_price" AS NUMBER)) AS "value"
  FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TRANSACTIONS"
),
top_10_balances AS (
  SELECT
    "address",
    SUM("value") AS "balance"
  FROM double_entry_book
  GROUP BY "address"
  ORDER BY "balance" DESC
  LIMIT 10
)
SELECT 
    ROUND(AVG("balance") / 1e15, 2) AS "average_balance_trillion"
FROM top_10_balances;
Database: ETHEREUM_BLOCKCHAIN (snowflake)
Question: Calculate the total circulating supply of 'BNB' tokens (in units divided by 10^18) by summing balances of all non-zero addresses, where each address’s balance equals its total received BNB minus sent BNB. Exclude transactions involving the zero address (0x000...) for both senders and receivers.
SQL:
WITH tokenInfo AS (
    SELECT "address"
    FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TOKENS"
    WHERE "name" = 'BNB'
),

receivedTx AS (
    SELECT "tx"."to_address" AS "addr", 
           "tokens"."name" AS "name", 
           SUM(CAST("tx"."value" AS FLOAT) / POWER(10, 18)) AS "amount_received"
    FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TOKEN_TRANSFERS" AS "tx"
    JOIN tokenInfo ON "tx"."token_address" = tokenInfo."address"
    JOIN "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TOKENS" AS "tokens"
      ON "tx"."token_address" = "tokens"."address"
    WHERE "tx"."to_address" <> '0x0000000000000000000000000000000000000000'
    GROUP BY "tx"."to_address", "tokens"."name"
),

sentTx AS (
    SELECT "tx"."from_address" AS "addr", 
           "tokens"."name" AS "name", 
           SUM(CAST("tx"."value" AS FLOAT) / POWER(10, 18)) AS "amount_sent"
    FROM "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TOKEN_TRANSFERS" AS "tx"
    JOIN tokenInfo ON "tx"."token_address" = tokenInfo."address"
    JOIN "ETHEREUM_BLOCKCHAIN"."ETHEREUM_BLOCKCHAIN"."TOKENS" AS "tokens"
      ON "tx"."token_address" = "tokens"."address"
    WHERE "tx"."from_address" <> '0x0000000000000000000000000000000000000000'
    GROUP BY "tx"."from_address", "tokens"."name"
),

walletBalances AS (
    SELECT r."addr",
           COALESCE(SUM(r."amount_received"), 0) - COALESCE(SUM(s."amount_sent"), 0) AS "balance"
    FROM receivedTx AS r
    LEFT JOIN sentTx AS s
      ON r."addr" = s."addr"
    GROUP BY r."addr"
)

SELECT 
    SUM("balance") AS "circulating_supply"
FROM walletBalances;
Database: ETHEREUM_BLOCKCHAIN (snowflake)
Question: Generate a comprehensive report of all Ethereum addresses active before January 1, 2017, calculating their net balances (adjusted for transaction fees and excluding delegatecall/callcode/staticcall transactions), hourly activity patterns, active days, incoming/outgoing transaction metrics (counts, unique counterparties, average ETH transfers), ERC20 token interactions (in/out counts, unique tokens, counterparties), mining rewards, contract creation frequency, failed transaction counts, and contract bytecode sizes, with all ETH values converted to standard units (divided by 10^18) and excluding addresses with no transaction history.
SQL:
Database: ghcn_d (snowflake)
Question: I want to know the IDs, names of weather stations within a 50 km straight-line distance from the center of Chicago (41.8319°N, 87.6847°W)
SQL:
WITH params AS (
  SELECT ST_GeogPoint(-87.6847, 41.8319) AS center,
         50 AS maxdist_km
),
distance_from_center AS (
  SELECT
    id,
    name,
    state,
    ST_GeogPoint(longitude, latitude) AS loc,
    ST_Distance(ST_GeogPoint(longitude, latitude), params.center) AS dist_meters
  FROM
    `bigquery-public-data.ghcn_d.ghcnd_stations`,
    params
  WHERE ST_DWithin(ST_GeogPoint(longitude, latitude), params.center, params.maxdist_km*1000)
),
nearest_stations AS (
  SELECT 
    *, 
    RANK() OVER (ORDER BY dist_meters ASC) AS rank
  FROM 
    distance_from_center
),
nearest_nstations AS (
  SELECT 
    station.* 
  FROM 
    nearest_stations AS station, params
)
SELECT * from nearest_nstations
Database: ghcn_d (snowflake)
Question: Could you provide the highest recorded precipitation, minimum temperature, and maximum temperature from the last 15 days of each year from 2013 to 2016 at weather station USW00094846? Ensure each value represents the peak measurement for that period, with precipitation in millimeters and temperatures in degrees Celsius, using only validated data (non-null values and no quality flags)
SQL:
WITH data AS (
  SELECT
    EXTRACT(YEAR FROM wx.date) AS year,
    MAX(IF(wx.element = 'PRCP', wx.value/10, NULL)) AS max_prcp,
    MAX(IF(wx.element = 'TMIN', wx.value/10, NULL)) AS max_tmin,
    MAX(IF(wx.element = 'TMAX', wx.value/10, NULL)) AS max_tmax
  FROM
    `bigquery-public-data.ghcn_d.ghcnd_2013` AS wx
  WHERE
    wx.id = 'USW00094846' AND
    wx.qflag IS NULL AND
    wx.value IS NOT NULL AND
    DATE_DIFF(DATE('2013-12-31'), wx.date, DAY) < 15
  GROUP BY
    year

  UNION ALL

  SELECT
    EXTRACT(YEAR FROM wx.date) AS year,
    MAX(IF(wx.element = 'PRCP', wx.value/10, NULL)) AS max_prcp,
    MAX(IF(wx.element = 'TMIN', wx.value/10, NULL)) AS max_tmin,
    MAX(IF(wx.element = 'TMAX', wx.value/10, NULL)) AS max_tmax
  FROM
    `bigquery-public-data.ghcn_d.ghcnd_2014` AS wx
  WHERE
    wx.id = 'USW00094846' AND
    wx.qflag IS NULL AND
    wx.value IS NOT NULL AND
    DATE_DIFF(DATE('2014-12-31'), wx.date, DAY) < 15
  GROUP BY
    year

  UNION ALL

  SELECT
    EXTRACT(YEAR FROM wx.date) AS year,
    MAX(IF(wx.element = 'PRCP', wx.value/10, NULL)) AS max_prcp,
    MAX(IF(wx.element = 'TMIN', wx.value/10, NULL)) AS max_tmin,
    MAX(IF(wx.element = 'TMAX', wx.value/10, NULL)) AS max_tmax
  FROM
    `bigquery-public-data.ghcn_d.ghcnd_2015` AS wx
  WHERE
    wx.id = 'USW00094846' AND
    wx.qflag IS NULL AND
    wx.value IS NOT NULL AND
    DATE_DIFF(DATE('2015-12-31'), wx.date, DAY) < 15
  GROUP BY
    year

  UNION ALL

  SELECT
    EXTRACT(YEAR FROM wx.date) AS year,
    MAX(IF(wx.element = 'PRCP', wx.value/10, NULL)) AS max_prcp,
    MAX(IF(wx.element = 'TMIN', wx.value/10, NULL)) AS max_tmin,
    MAX(IF(wx.element = 'TMAX', wx.value/10, NULL)) AS max_tmax
  FROM
    `bigquery-public-data.ghcn_d.ghcnd_2016` AS wx
  WHERE
    wx.id = 'USW00094846' AND
    wx.qflag IS NULL AND
    wx.value IS NOT NULL AND
    DATE_DIFF(DATE('2016-12-31'), wx.date, DAY) < 15
  GROUP BY
    year
)

SELECT
  year,
  MAX(max_prcp) AS annual_max_prcp,
  MAX(max_tmin) AS annual_max_tmin,
  MAX(max_tmax) AS annual_max_tmax
FROM data
GROUP BY year
ORDER BY year ASC;
Database: new_york_ghcn (snowflake)
Question: Calculate the average daily number of Citibike trips in New York City during 2016, categorizing days as rainy if the total precipitation exceeds 5 millimeters (obtained by dividing the raw precipitation value by 10), and non-rainy otherwise. Use data from the nearest GHCN station located within 50 km of (40.7128, -74.0060) that has valid, unflagged measurements, then compare the resulting average Citibike trips on rainy days versus non-rainy days.
SQL:
Database: new_york (snowflake)
Question: Calculate the change in the number of living trees of each fall color in New York City from 1995 to 2015 by computing, for each tree species, the difference between the number of trees not marked as dead in 1995 and the number of trees alive in 2015, matching species by the uppercase form of their scientific names from the tree_species table. Then, group the species by their fall color and sum these differences to determine the total change in the number of trees for each fall color.
SQL:
SELECT
  c.fall_color,
  SUM(d.count_growth) AS change
FROM (
  SELECT
    fall_color,
    UPPER(species_scientific_name) AS latin
  FROM
    `bigquery-public-data.new_york.tree_species`)c
JOIN (
  SELECT
    IFNULL(a.upper_latin,
      b.upper_latin) AS latin,
    (IFNULL(count_2015,
        0)-IFNULL(count_1995,
        0)) AS count_growth
  FROM (
    SELECT
      UPPER(spc_latin) AS upper_latin,
      spc_common,
      COUNT(*) AS count_2015
    FROM
      `bigquery-public-data.new_york.tree_census_2015`
    WHERE
      status="Alive"
    GROUP BY
      spc_latin,
      spc_common)a
  FULL OUTER JOIN (
    SELECT
      UPPER(spc_latin) AS upper_latin,
      COUNT(*) AS count_1995
    FROM
      `bigquery-public-data.new_york.tree_census_1995`
    WHERE
      status !="Dead"
    GROUP BY
      spc_latin)b
  ON
    a.upper_latin=b.upper_latin
  ORDER BY
    count_growth DESC)d
ON
  d.latin=c.latin
GROUP BY
  fall_color
ORDER BY
  change DESC
Database: new_york (snowflake)
Question: For the top 20 Citi Bike routes in 2016, which route is faster than yellow taxis and among those, which one has the longest average bike duration? Please provide the start station name of this route. The coordinates are rounded to three decimals.
SQL:
WITH top20route AS (
SELECT
  start_station_name, end_station_name, avg_bike_duration, avg_taxi_duration
FROM (
  SELECT
    start_station_name,
    end_station_name,
    ROUND(start_station_latitude, 3) AS ss_lat,
    ROUND(start_station_longitude, 3) AS ss_long,
    ROUND(end_station_latitude, 3) AS es_lat,
    ROUND(end_station_longitude, 3) AS es_long,
    AVG(tripduration) AS avg_bike_duration,
    COUNT(*) AS bike_trips
  FROM
    `bigquery-public-data.new_york.citibike_trips`
  WHERE 
  EXTRACT(YEAR from starttime) = 2016 AND
    start_station_name != end_station_name
  GROUP BY
    start_station_name, end_station_name, ss_lat, ss_long, es_lat, es_long
  ORDER BY
    bike_trips DESC
  LIMIT
    20
) a
JOIN (
  SELECT
    ROUND(pickup_latitude, 3) AS pu_lat,
    ROUND(pickup_longitude, 3) AS pu_long,
    ROUND(dropoff_latitude, 3) AS do_lat,
    ROUND(dropoff_longitude, 3) AS do_long,
    AVG(UNIX_SECONDS(dropoff_datetime)-UNIX_SECONDS(pickup_datetime)) AS avg_taxi_duration,
    COUNT(*) AS taxi_trips
  FROM
    `bigquery-public-data.new_york.tlc_yellow_trips_2016`
  GROUP BY
    pu_lat, pu_long, do_lat, do_long
) b
ON
  a.ss_lat = b.pu_lat AND
  a.es_lat = b.do_lat AND
  a.ss_long = b.pu_long AND
  a.es_long = b.do_long
)

SELECT start_station_name
FROM top20route
WHERE avg_bike_duration < avg_taxi_duration
ORDER BY
avg_bike_duration
DESC
LIMIT 1
Database: new_york_plus (snowflake)
Question: What is the average trip duration in minutes for all valid Yellow taxi trips that took place between February 1, 2016, and February 7, 2016 (inclusive), with a positive trip duration, more than three passengers, and a trip distance of at least ten miles, where both the pickup and dropoff locations are in Brooklyn?
SQL:
SELECT 
    AVG(TIMESTAMP_DIFF(dropoff_datetime, pickup_datetime, SECOND) / 60.0) AS average_trip_duration_in_minutes
FROM
(
    SELECT *
    FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2016` t
    WHERE 
        pickup_datetime BETWEEN '2016-02-01' AND '2016-02-07' AND 
        dropoff_datetime BETWEEN '2016-02-01' AND '2016-02-07' AND
        TIMESTAMP_DIFF(dropoff_datetime, pickup_datetime, SECOND) > 0 AND 
        passenger_count > 3 AND 
        trip_distance >= 10
) t
INNER JOIN `bigquery-public-data.new_york_taxi_trips.taxi_zone_geom` tz
ON t.pickup_location_id = tz.zone_id
INNER JOIN `bigquery-public-data.new_york_taxi_trips.taxi_zone_geom` tz1
ON t.dropoff_location_id = tz1.zone_id
WHERE 
    tz.borough = "Brooklyn" AND
    tz1.borough = "Brooklyn";
Database: new_york_plus (snowflake)
Question: For NYC yellow taxi trips between January 1 and January 7, 2016, excluding any trips picked up in ‘EWR’ or ‘Staten Island,’ determine the proportion of rides that fall into each tip category in each pickup borough. Only include trips where the dropoff time is after the pickup time, the passenger count is greater than zero, and trip_distance, tip_amount, tolls_amount, mta_tax, fare_amount, and total_amount are all non-negative. Classify the tip percentage as follows: 0% (no tip), up to 5%, 5% to 10%, 10% to 15%, 15% to 20%, 20% to 25%, and more than 25%.
SQL:
Database: new_york_plus (snowflake)
Question: Find the top 10 taxi trips in New York City between July 1 and July 7, 2016 (ensuring both pickup and dropoff times fall within these dates) where the passenger count is greater than five, the trip distance is at least ten miles, and there are no negative fare-related amounts (including tip, tolls, mta tax, fare, and total costs). Exclude any trips where the dropoff time is not strictly after the pickup time, then sort the results by total fare amount in descending order. Finally, display each trip’s pickup zone, dropoff zone, trip duration in seconds, driving speed in miles per hour, and tip rate as a percentage of the total fare amount.
SQL:
SELECT 
    tz.zone_name AS pickup_zone,
    tz1.zone_name AS dropoff_zone, 
    time_duration_in_secs,
    driving_speed_miles_per_hour,
    tip_rate
FROM
(
SELECT *,
    TIMESTAMP_DIFF(dropoff_datetime,pickup_datetime,SECOND) as time_duration_in_secs,
    ROUND(trip_distance / (TIMESTAMP_DIFF(dropoff_datetime, pickup_datetime, SECOND) / 3600), 2) AS driving_speed_miles_per_hour,
    (CASE WHEN total_amount=0 THEN 0
          ELSE (tip_amount*100/total_amount) END) as tip_rate
FROM `bigquery-public-data.new_york_taxi_trips.tlc_yellow_trips_2016`
) t
INNER JOIN `bigquery-public-data.new_york_taxi_trips.taxi_zone_geom` tz
ON t.pickup_location_id = tz.zone_id
INNER JOIN `bigquery-public-data.new_york_taxi_trips.taxi_zone_geom` tz1
ON t.dropoff_location_id = tz1.zone_id
WHERE 
    pickup_datetime BETWEEN '2016-07-01' AND '2016-07-07' 
    AND dropoff_datetime BETWEEN '2016-07-01' AND '2016-07-07'
    AND TIMESTAMP_DIFF(dropoff_datetime,pickup_datetime,SECOND) > 0
    AND passenger_count > 5
    AND trip_distance >= 10
    AND tip_amount >= 0 
    AND tolls_amount >= 0 
    AND mta_tax >= 0 
    AND fare_amount >= 0
    AND total_amount >= 0
ORDER BY total_amount DESC
LIMIT 10;
Database: new_york_plus (snowflake)
Question: For each New York City borough, how many subway stations are there in total, how many have at least one entrance that is marked both as an actual entry and as ADA-compliant, and what percentage of the total stations in each borough does this represent, listing boroughs from the highest to the lowest percentage?
SQL:
WITH stations_n_entrances AS (
      SELECT borough_name,s.station_name,entry,ada_compliant
      FROM `bigquery-public-data.new_york_subway.stations` s
      JOIN `bigquery-public-data.new_york_subway.station_entrances` se
      ON s.station_name = se.station_name
      )

SELECT se.borough_name, COUNT(DISTINCT se.station_name) num_stations,
      COUNT(DISTINCT adas.station_name) num_stations_w_compliant_entrance, 
      (100*COUNT(DISTINCT adas.station_name))/(COUNT(DISTINCT se.station_name)) percent_compliant_stations
FROM `stations_n_entrances` se
LEFT JOIN `stations_n_entrances` adas
ON se.station_name = adas.station_name
AND adas.entry AND adas.ada_compliant
GROUP BY 1
ORDER BY 4 DESC
Database: san_francisco (snowflake)
Question: What is the total distance traveled by each bike in the San Francisco Bikeshare program, measured in meters? Use data from bikeshare trips and stations to calculate this.
SQL:
SELECT
  bike_number, 
  AVG(dist_in_m) AS avg_dist_m, 
  SUM(dist_in_m) AS total_dist_m
FROM (
  SELECT
    ST_DISTANCE(
      ST_GEOGPOINT(start_lon, start_lat),
      ST_GEOGPOINT(end_lon, end_lat)
    ) AS dist_in_m,
    starts.bike_number
  FROM (
    SELECT 
      latitude AS start_lat,
      longitude AS start_lon,
      bike_number,
      trip_id
    FROM `bigquery-public-data.san_francisco.bikeshare_trips` trips
    LEFT JOIN `bigquery-public-data.san_francisco.bikeshare_stations` stations
      ON trips.start_station_id = stations.station_id
  ) starts
  LEFT JOIN (
    SELECT 
      latitude AS end_lat,
      longitude AS end_lon,
      bike_number,
      trip_id
    FROM `bigquery-public-data.san_francisco.bikeshare_trips` trips
    LEFT JOIN `bigquery-public-data.san_francisco.bikeshare_stations` stations
      ON trips.end_station_id = stations.station_id
  ) ends ON ends.trip_id = starts.trip_id
)
GROUP BY bike_number
ORDER BY total_dist_m DESC
Database: san_francisco (snowflake)
Question: Please find, for each year-month combination (in the format YYYYMM) derived from the start date of bike share trips in San Francisco, the first trip duration in minutes, the last trip duration in minutes, the highest trip duration in minutes, and the lowest trip duration in minutes, where ‘first’ and ‘last’ are determined by the chronological order of the trip start date, then group your results by this year-month and sort them by the same year-month key.
SQL:
Database: san_francisco_plus (snowflake)
Question: Find the latest ride data for each region between 2014 and 2017. I want to know the name of each region, the trip ID of this ride, the ride duration, the start time, the starting station, and the gender of the rider.
SQL:
SELECT t1.*
  FROM 
  (SELECT Trips.trip_id TripId,
               Trips.duration_sec TripDuration,
               Trips.start_date TripStartDate,
               Trips.start_station_name TripStartStation,
               Trips.member_gender Gender,
               Regions.name RegionName
          FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_trips` Trips
         INNER JOIN `bigquery-public-data.san_francisco_bikeshare.bikeshare_station_info` StationInfo
            ON CAST(Trips.start_station_id AS STRING) = CAST(StationInfo.station_id AS STRING)
         INNER JOIN `bigquery-public-data.san_francisco_bikeshare.bikeshare_regions` Regions
            ON StationInfo.region_id = Regions.region_id
         WHERE (EXTRACT(YEAR from Trips.start_date)) BETWEEN 2014 AND 2017
           ) 
           t1
 RIGHT JOIN (SELECT MAX(start_date) TripStartDate,
                   Regions.name RegionName
              FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_station_info` StationInfo
             INNER JOIN `bigquery-public-data.san_francisco_bikeshare.bikeshare_trips` Trips
                ON CAST(StationInfo.station_id AS STRING) = CAST(Trips.start_station_id AS STRING)
             INNER JOIN `bigquery-public-data.san_francisco_bikeshare.bikeshare_regions` Regions
                ON Regions.region_id = StationInfo.region_id
                 WHERE (EXTRACT(YEAR from Trips.start_date) BETWEEN 2014 AND 2017
           AND Regions.name IS NOT NULL)
             GROUP BY RegionName) 
             t2
    ON t1.RegionName = t2.RegionName AND t1.TripStartDate = t2.TripStartDate