nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: GITHUB_REPOS_DATE (snowflake)
Question: Which repository with an approved license in `licenses.md` had the highest combined total of forks, issues, and watches in April 2022?
SQL:
WITH allowed_repos AS (
    SELECT 
        "repo_name",
        "license"
    FROM 
        GITHUB_REPOS_DATE.GITHUB_REPOS.LICENSES
    WHERE 
        "license" IN (
            'gpl-3.0', 'artistic-2.0', 'isc', 'cc0-1.0', 'epl-1.0', 'gpl-2.0',
            'mpl-2.0', 'lgpl-2.1', 'bsd-2-clause', 'apache-2.0', 'mit', 'lgpl-3.0'
        )
),
watch_counts AS (
    SELECT 
        TRY_PARSE_JSON("repo"):"name"::STRING AS "repo",
        COUNT(DISTINCT TRY_PARSE_JSON("actor"):"login"::STRING) AS "watches"
    FROM 
        GITHUB_REPOS_DATE.MONTH._202204
    WHERE 
        "type" = 'WatchEvent'
    GROUP BY 
        TRY_PARSE_JSON("repo"):"name"
),
issue_counts AS (
    SELECT 
        TRY_PARSE_JSON("repo"):"name"::STRING AS "repo",
        COUNT(*) AS "issue_events"
    FROM 
        GITHUB_REPOS_DATE.MONTH._202204
    WHERE 
        "type" = 'IssuesEvent'
    GROUP BY 
        TRY_PARSE_JSON("repo"):"name"
),
fork_counts AS (
    SELECT 
        TRY_PARSE_JSON("repo"):"name"::STRING AS "repo",
        COUNT(*) AS "forks"
    FROM 
        GITHUB_REPOS_DATE.MONTH._202204
    WHERE 
        "type" = 'ForkEvent'
    GROUP BY 
        TRY_PARSE_JSON("repo"):"name"
)
SELECT 
    ar."repo_name"
FROM 
    allowed_repos AS ar
INNER JOIN 
    fork_counts AS fc ON ar."repo_name" = fc."repo"
INNER JOIN 
    issue_counts AS ic ON ar."repo_name" = ic."repo"
INNER JOIN 
    watch_counts AS wc ON ar."repo_name" = wc."repo"
ORDER BY 
    (fc."forks" + ic."issue_events" + wc."watches") DESC
LIMIT 1;
Database: GITHUB_REPOS_DATE (snowflake)
Question: Find the most active Python repository on GitHub based on watcher count, issues, and forks. The query should select repositories with specific open-source licenses (`artistic-2.0`, `isc`, `mit`, `apache-2.0`), count distinct watchers, issue events, and forks for each repository in April 2022, and include only those with `.py` files on the `master` branch. Join the license data with watch counts, issue events, and fork counts, then sort by a combined metric of forks, issues, and watches, returning the name and count of the most active repository.
SQL:
Database: GITHUB_REPOS (snowflake)
Question: Can you analyze the joined data from github repos files and github_repos contents, focusing only on files ending with '.py' or '.r', then extract Python modules from 'import' or 'from ... import' lines and R libraries from 'library(...)' lines, count their occurrences, and finally list the results sorted by language and by the number of occurrences in descending order?
SQL:
WITH extracted_modules AS (
SELECT 
    el."file_id" AS "file_id", 
    el."repo_name", 
    el."path" AS "path_", 
    REPLACE(line.value, '"', '') AS "line_",
    CASE
        WHEN ENDSWITH(el."path", '.py') THEN 'python'
        WHEN ENDSWITH(el."path", '.r') THEN 'r'
        ELSE NULL
    END AS "language",
    CASE
        WHEN ENDSWITH(el."path", '.py') THEN
            ARRAY_CAT(
                ARRAY_CONSTRUCT(REGEXP_SUBSTR(line.value, '\\bimport\\s+(\\w+)', 1, 1, 'e')),
                ARRAY_CONSTRUCT(REGEXP_SUBSTR(line.value, '\\bfrom\\s+(\\w+)', 1, 1, 'e'))
            )
        WHEN ENDSWITH(el."path", '.r') THEN
            ARRAY_CONSTRUCT(REGEXP_SUBSTR(line.value, 'library\\s*\\(\\s*([^\\s)]+)\\s*\\)', 1, 1, 'e'))
        ELSE ARRAY_CONSTRUCT()
    END AS "modules"
FROM (
    SELECT
        ct."id" AS "file_id", 
        fl."repo_name" AS "repo_name", 
        fl."path", 
        SPLIT(REPLACE(ct."content", '\n', ' \n'), '\n') AS "lines"
    FROM 
        GITHUB_REPOS_DATE.GITHUB_REPOS.SAMPLE_FILES AS fl
    JOIN 
        GITHUB_REPOS_DATE.GITHUB_REPOS.SAMPLE_CONTENTS AS ct 
        ON fl."id" = ct."id"
) AS el,
LATERAL FLATTEN(input => el."lines") AS line 
WHERE
    (
        ENDSWITH("path_", '.py') 
        AND 
        (
            "line_" LIKE 'import %' 
            OR 
            "line_" LIKE 'from %'
        )
    )
    OR
    (
        ENDSWITH("path_", '.r') 
        AND 
        "line_" LIKE 'library%('
    )

),
module_counts AS (
    SELECT 
        em."language",
        f.value::STRING AS "module",
        COUNT(*) AS "occurrence_count"
    FROM 
        extracted_modules AS em,
        LATERAL FLATTEN(input => em."modules") AS f
    WHERE 
        em."modules" IS NOT NULL
        AND f.value IS NOT NULL
    GROUP BY 
        em."language", 
        f.value
),
python AS (
    SELECT 
        "language",
        "module",
        "occurrence_count"
    FROM 
        module_counts
    WHERE 
        "language" = 'python'
),
rlanguage AS (
    SELECT 
        "language",
        "module",
        "occurrence_count"
    FROM 
        module_counts AS mc_inner
    WHERE 
        "language" = 'r'
)
SELECT 
    *
FROM 
    python
UNION ALL
SELECT 
    *
FROM 
    rlanguage
ORDER BY 
    "language", 
    "occurrence_count" DESC;
Database: GITHUB_REPOS (snowflake)
Question: Among all repositories that do not use any programming language whose name (case-insensitively) includes the substring "python," what is the proportion of files whose paths include "readme.md" and whose contents contain the phrase "Copyright (c)"?
SQL:
WITH requests AS (
    SELECT 
        D."id",
        D."content",
        E."repo_name",
        E."path"
    FROM 
        (
            SELECT 
                "id",
                "content"
            FROM 
                GITHUB_REPOS.GITHUB_REPOS.SAMPLE_CONTENTS
            GROUP BY 
                "id", "content"
        ) AS D
    INNER JOIN 
        (
            SELECT 
                C."id",
                C."repo_name",
                C."path"
            FROM 
                (
                    SELECT 
                        "id",
                        "repo_name",
                        "path"
                    FROM 
                        GITHUB_REPOS.GITHUB_REPOS.SAMPLE_FILES
                    WHERE 
                        LOWER("path") LIKE '%readme.md'
                    GROUP BY 
                        "path", "id", "repo_name"
                ) AS C
            INNER JOIN 
                (
                    SELECT 
                        "repo_name",
                        language_struct.value:"name"::STRING AS "language_name"
                    FROM 
                        GITHUB_REPOS.GITHUB_REPOS.LANGUAGES,
                        LATERAL FLATTEN(input => "language") AS language_struct
                    WHERE 
                        LOWER(language_struct.value:"name"::STRING) NOT LIKE '%python%'
                    GROUP BY 
                        "language_name", "repo_name"
                ) AS F
            ON 
                C."repo_name" = F."repo_name"
        ) AS E
    ON 
        D."id" = E."id"
)
SELECT 
    (SELECT COUNT(*) FROM requests WHERE "content" LIKE '%Copyright (c)%') / COUNT(*) AS "proportion"
FROM 
    requests;
Database: GITHUB_REPOS (snowflake)
Question: Retrieve all non-empty, non-commented lines from `README.md` files in GitHub repositories, excluding lines that are comments (either starting with `#` for Markdown or `//` for code comments). For each line, calculate how often each unique line appears across all repositories and return a comma-separated list of the programming languages used in each repository containing that line, sorted alphabetically, with the results ordered by the frequency of occurrence in descending order.
SQL:
WITH content_extracted AS (
    SELECT 
        "D"."id" AS "id",
        "repo_name",
        "path",
        SPLIT("content", '\n') AS "lines",
        "language_name"
    FROM 
        (
            SELECT 
                "id",
                "content"
            FROM 
                "GITHUB_REPOS"."GITHUB_REPOS"."SAMPLE_CONTENTS"
        ) AS "D"
    INNER JOIN 
        (
            SELECT 
                "id",
                "C"."repo_name" AS "repo_name",
                "path",
                "language_name"
            FROM 
                (
                    SELECT 
                        "id",
                        "repo_name",
                        "path"
                    FROM 
                        "GITHUB_REPOS"."GITHUB_REPOS"."SAMPLE_FILES"
                    WHERE 
                        LOWER("path") LIKE '%readme.md'
                ) AS "C"
            INNER JOIN 
                (
                    SELECT 
                        "repo_name",
                        "language_struct".value:"name" AS "language_name"
                    FROM 
                        (
                            SELECT 
                                "repo_name", 
                                "language"
                            FROM 
                                "GITHUB_REPOS"."GITHUB_REPOS"."LANGUAGES"
                        )
                    CROSS JOIN 
                        LATERAL FLATTEN(INPUT => "language") AS "language_struct"
                ) AS "F"
            ON 
                "C"."repo_name" = "F"."repo_name"
        ) AS "E"
    ON 
        "E"."id" = "D"."id"
),
non_empty_lines AS (
    SELECT 
        "line".value AS "line_",
        "language_name"
    FROM 
        content_extracted,
        LATERAL FLATTEN(INPUT => "lines") AS "line"
    WHERE 
        TRIM("line".value) != ''
        AND NOT STARTSWITH(TRIM("line".value), '#')
        AND NOT STARTSWITH(TRIM("line".value), '//')
),
aggregated_languages AS (
    SELECT 
        "line_",
        COUNT(*) AS "frequency",
        ARRAY_AGG("language_name") AS "languages"
    FROM 
        non_empty_lines
    GROUP BY 
        "line_"
)

SELECT 
    REGEXP_REPLACE("line_", '^"|"$', '') AS "line",
    "frequency",
    ARRAY_TO_STRING(ARRAY_SORT("languages"), ', ') AS "languages_sorted"
FROM 
    aggregated_languages
ORDER BY 
    "frequency" DESC;
Database: GITHUB_REPOS_DATE (snowflake)
Question: Using the 2017 GitHub Archive data for watch events, which three repositories that include at least one Python file (with a .py extension) smaller than 15,000 bytes and containing the substring "def " in its content have the highest total number of watch events for that year?
SQL:
WITH watched_repos AS (
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201701
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201702
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201703
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201704
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201705
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201706
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201707
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201708
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201709
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201710
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201711
    WHERE
        "type" = 'WatchEvent'
    UNION ALL
    SELECT
        PARSE_JSON("repo"):"name"::STRING AS "repo"
    FROM 
        GITHUB_REPOS_DATE.MONTH._201712
    WHERE
        "type" = 'WatchEvent'
),

repo_watch_counts AS (
    SELECT
        "repo",
        COUNT(*) AS "watch_count"
    FROM
        watched_repos
    GROUP BY
        "repo"
)

SELECT
    REPLACE(r."repo", '"', '') AS "repo",
    r."watch_count"
FROM
    GITHUB_REPOS_DATE.GITHUB_REPOS.SAMPLE_FILES AS f
JOIN
    GITHUB_REPOS_DATE.GITHUB_REPOS.SAMPLE_CONTENTS AS c
    ON f."id" = c."id"
JOIN 
    repo_watch_counts AS r
    ON f."repo_name" = r."repo"
WHERE
    f."path" LIKE '%.py' 
    AND c."size" < 15000 
    AND POSITION('def ' IN c."content") > 0
GROUP BY
    r."repo", r."watch_count"
ORDER BY
    r."watch_count" DESC
LIMIT 
    3;
Database: GITHUB_REPOS (snowflake)
Question: Please provide a report on the number of occurrences of specific line types across files from the GitHub repository. Categorize a line as 'trailing' if it ends with a blank character, as 'Space' if it starts with a space, and as 'Other' if it meets neither condition. The report should include the total number of occurrences for each category, considering all lines across all files.
SQL:
Database: GITHUB_REPOS (snowflake)
Question: How many commit messages are there in repositories that use the 'Shell' programming language and 'apache-2.0' license, where the length of the commit message is more than 5 characters but less than 10,000 characters, and the messages do not start with the word 'merge', 'update' or 'test'?
SQL:
SELECT
  COUNT(commits_table."message") AS "num_messages"
FROM (
  SELECT
    L."repo_name",
    language_struct.value:"name"::STRING AS "language_name"
  FROM
    GITHUB_REPOS.GITHUB_REPOS.LANGUAGES AS L,
    LATERAL FLATTEN(input => L."language") AS language_struct
) AS lang_table
JOIN 
  GITHUB_REPOS.GITHUB_REPOS.LICENSES AS license_table
ON 
  license_table."repo_name" = lang_table."repo_name"
JOIN (
  SELECT
    *
  FROM
    GITHUB_REPOS.GITHUB_REPOS.SAMPLE_COMMITS
) AS commits_table
ON 
  commits_table."repo_name" = lang_table."repo_name"
WHERE
  license_table."license" LIKE 'apache-2.0'
  AND lang_table."language_name" LIKE 'Shell'
  AND LENGTH(commits_table."message") > 5
  AND LENGTH(commits_table."message") < 10000
  AND LOWER(commits_table."message") NOT LIKE 'update%'
  AND LOWER(commits_table."message") NOT LIKE 'test%'
  AND LOWER(commits_table."message") NOT LIKE 'merge%';
Database: GITHUB_REPOS (snowflake)
Question: Extract and count the frequency of all package names listed in the require section of JSON-formatted content
SQL:
WITH json_files AS (
  SELECT
    c."id",
    TRY_PARSE_JSON(c."content"):"require" AS "dependencies"
  FROM
    GITHUB_REPOS.GITHUB_REPOS.SAMPLE_CONTENTS c
),
package_names AS (
  SELECT
    f.key AS "package_name"
  FROM
    json_files,
    LATERAL FLATTEN(input => "dependencies") AS f
)
SELECT
  "package_name",
  COUNT(*) AS "count"
FROM
  package_names
WHERE
  "package_name" IS NOT NULL
GROUP BY
  "package_name"
ORDER BY
  "count" DESC;
Database: GITHUB_REPOS (snowflake)
Question: List the repository names and commit counts for the top two GitHub repositories with JavaScript as the primary language and the highest number of commits.
SQL:
WITH repositories AS (
    SELECT
        t2."repo_name",
        t2."language"
    FROM (
        SELECT
            t1."repo_name",
            t1."language",
            RANK() OVER (PARTITION BY t1."repo_name" ORDER BY t1."language_bytes" DESC) AS "rank"
        FROM (
            SELECT
                l."repo_name",
                lang.value:"name"::STRING AS "language",
                lang.value:"bytes"::NUMBER AS "language_bytes"
            FROM
                GITHUB_REPOS.GITHUB_REPOS.LANGUAGES AS l,
                LATERAL FLATTEN(input => l."language") AS lang
        ) AS t1
    ) AS t2
    WHERE t2."rank" = 1
),
python_repo AS (
    SELECT
        "repo_name",
        "language"
    FROM
        repositories
    WHERE
        "language" = 'JavaScript'
)
SELECT 
    sc."repo_name", 
    COUNT(sc."commit") AS "num_commits"
FROM 
    GITHUB_REPOS.GITHUB_REPOS.SAMPLE_COMMITS AS sc
INNER JOIN 
    python_repo 
ON 
    python_repo."repo_name" = sc."repo_name"
GROUP BY 
    sc."repo_name"
ORDER BY 
    "num_commits" DESC
LIMIT 2;
Database: GITHUB_REPOS (snowflake)
Question: Could you please find the name of the repository that contains the most copied non-binary Swift file in the dataset, ensuring each file is uniquely identified by its ID?
SQL:
WITH selected_repos AS (
  SELECT
    f."id",
    f."repo_name" AS "repo_name",
    f."path" AS "path"
  FROM
    GITHUB_REPOS.GITHUB_REPOS.SAMPLE_FILES AS f
),
deduped_files AS (
  SELECT
    f."id",
    MIN(f."repo_name") AS "repo_name",
    MIN(f."path") AS "path"
  FROM
    selected_repos AS f
  GROUP BY
    f."id"
)
SELECT
  f."repo_name"
FROM
  deduped_files AS f
  JOIN GITHUB_REPOS.GITHUB_REPOS.SAMPLE_CONTENTS AS c 
  ON f."id" = c."id"
WHERE
  NOT c."binary"
  AND f."path" LIKE '%.swift'
ORDER BY c."copies" DESC
LIMIT 1;
Database: PYPI (snowflake)
Question: I want to know the GitHub project URLs for the top 3 most downloaded PyPI packages based on download count. First, extract PyPI package metadata including name, version, and project URLs. Filter these URLs to only include those that link to GitHub repositories. Use a regular expression to clean the GitHub URLs by removing unnecessary parts like 'issues', 'pull', 'blob', and 'tree' paths, keeping only the main repository URL. For packages with multiple versions, use only the most recent version based on upload time. Join this data with download metrics to determine the most downloaded packages. Return only the cleaned GitHub repository URLs (without quotation marks) for the top 3 packages by total download count, ensuring that only packages with valid GitHub URLs are included in the results.
SQL:
Database: cms_data (snowflake)
Question: What is the most prescribed medication in each state in 2014?
SQL:
SELECT
  A.state,
  drug_name,
  total_claim_count
FROM (
  SELECT
    generic_name AS drug_name,
    nppes_provider_state AS state,
    ROUND(SUM(total_claim_count)) AS total_claim_count,
    ROUND(SUM(total_day_supply)) AS day_supply,
    ROUND(SUM(total_drug_cost)) / 1e6 AS total_cost_millions
  FROM
    `bigquery-public-data.cms_medicare.part_d_prescriber_2014`
  GROUP BY
    state,
    drug_name) A
INNER JOIN (
  SELECT
    state,
    MAX(total_claim_count) AS max_total_claim_count
  FROM (
    SELECT
      nppes_provider_state AS state,
      ROUND(SUM(total_claim_count)) AS total_claim_count
    FROM
      `bigquery-public-data.cms_medicare.part_d_prescriber_2014`
    GROUP BY
      state,
      generic_name)
  GROUP BY
    state) B
ON
  A.state = B.state
  AND A.total_claim_count = B.max_total_claim_count;
Database: cms_data (snowflake)
Question: Can you tell me which healthcare provider incurs the highest combined average costs for both outpatient and inpatient services in 2014?
SQL:
SELECT
  Provider_Name
FROM
(
SELECT
  OP.provider_state AS State,
  OP.provider_city AS City,
  OP.provider_id AS Provider_ID,
  OP.provider_name AS Provider_Name,
  ROUND(OP.average_OP_cost) AS Average_OP_Cost,
  ROUND(IP.average_IP_cost) AS Average_IP_Cost,
  ROUND(OP.average_OP_cost + IP.average_IP_cost) AS Combined_Average_Cost
FROM (
  SELECT
    provider_state,
    provider_city,
    provider_id,
    provider_name,
    SUM(average_total_payments*outpatient_services)/SUM(outpatient_services) AS average_OP_cost
  FROM
    `bigquery-public-data.cms_medicare.outpatient_charges_2014`
  GROUP BY
    provider_state,
    provider_city,
    provider_id,
    provider_name ) AS OP
INNER JOIN (
  SELECT
    provider_state,
    provider_city,
    provider_id,
    provider_name,
    SUM(average_medicare_payments*total_discharges)/SUM(total_discharges) AS average_IP_cost
  FROM
    `bigquery-public-data.cms_medicare.inpatient_charges_2014`
  GROUP BY
    provider_state,
    provider_city,
    provider_id,
    provider_name ) AS IP
ON
  OP.provider_id = IP.provider_id
  AND OP.provider_state = IP.provider_state
  AND OP.provider_city = IP.provider_city
  AND OP.provider_name = IP.provider_name
ORDER BY
  combined_average_cost DESC
LIMIT
  1
);
Database: cms_data (snowflake)
Question: For the drug with the highest total number of prescriptions in New York State during 2014, could you list the top five states with the highest total claim counts for this drug? Please also include their total claim counts and total drug costs. 
SQL:
WITH ny_top_drug AS (
  SELECT
    drug_name AS drug_name,
    ROUND(SUM(total_claim_count)) AS total_claim_count
  FROM
    `bigquery-public-data.cms_medicare.part_d_prescriber_2014`
  WHERE
    nppes_provider_state = 'NY'
  GROUP BY
    drug_name
  ORDER BY
    total_claim_count DESC
  LIMIT 1
),
top_5_states AS (
  SELECT
    nppes_provider_state AS state,
    SUM(total_claim_count) AS total_claim_count,
    SUM(total_drug_cost) AS total_drug_cost
  FROM
    `bigquery-public-data.cms_medicare.part_d_prescriber_2014`
  WHERE
    drug_name = (SELECT drug_name FROM ny_top_drug)
  GROUP BY
    state
  ORDER BY
    total_claim_count DESC
  LIMIT 5
)
SELECT
  state,
  total_claim_count,
  total_drug_cost
FROM
  top_5_states;
Database: cms_data (snowflake)
Question: For the provider whose total inpatient Medicare cost from 2011 through 2015 is the highest (computed as the sum of average_medicare_payments multiplied by total_discharges), please list that provider’s yearly average inpatient cost and yearly average outpatient cost for each calendar year in this period, where the inpatient cost is calculated as the average of (average_medicare_payments × total_discharges) and the outpatient cost is calculated as the average of (average_total_payments × outpatient_services).
SQL:
Database: cms_data (snowflake)
Question: Could you provide the percentage of participants for standard acne, atopic dermatitis, psoriasis, and vitiligo as defined by the International Classification of Diseases 10-CM (ICD-10-CM), including their subcategories? Please include all related concepts mapped to the standard ICD-10-CM codes (L70 for acne, L20 for atopic dermatitis, L40 for psoriasis, and L80 for vitiligo) by utilizing concept relationships, including descendant concepts. The percentage should be calculated based on the total number of participants, considering only the standard concepts and their related descendants.
SQL:
WITH skin_condition_ICD_concept_ids AS (
    SELECT
        concept_id,
        CASE concept_code
            WHEN 'L70' THEN 'Acne'
            WHEN 'L20' THEN 'Atopic dermatitis'
            WHEN 'L40' THEN 'Psoriasis'
            ELSE 'Vitiligo'
        END AS skin_condition
    FROM
        `bigquery-public-data.cms_synthetic_patient_data_omop.concept`
    WHERE
        concept_code IN ('L70', 'L20', 'L40', 'L80')
        AND vocabulary_id = 'ICD10CM'
),
standard_concept_ids AS (
    SELECT
        concept_id
    FROM
        `bigquery-public-data.cms_synthetic_patient_data_omop.concept`
    WHERE
        standard_concept = 'S'
),
skin_condition_standard_concept_ids AS (
    SELECT
        s.skin_condition,
        r.concept_id_2 AS concept_id
    FROM
        skin_condition_ICD_concept_ids s
    JOIN
        `bigquery-public-data.cms_synthetic_patient_data_omop.concept_relationship` r
    ON
        s.concept_id = r.concept_id_1
    JOIN
        standard_concept_ids sc
    ON
        sc.concept_id = r.concept_id_2
    WHERE
        r.relationship_id = 'Maps to'
),
all_skin_concept_ids AS (
    SELECT DISTINCT
        skin_condition,
        concept_id
    FROM
        skin_condition_standard_concept_ids
),
descendant_concept_ids AS (
    SELECT
        a.skin_condition,
        ca.descendant_concept_id AS concept_id
    FROM
        all_skin_concept_ids a
    JOIN
        `bigquery-public-data.cms_synthetic_patient_data_omop.concept_ancestor` ca
    ON
        a.concept_id = ca.ancestor_concept_id
),
participants_with_condition AS (
    SELECT
        d.skin_condition,
        COUNT(DISTINCT co.person_id) AS nb_of_participants_with_skin_condition
    FROM
        `bigquery-public-data.cms_synthetic_patient_data_omop.condition_occurrence` co
    JOIN
        descendant_concept_ids d
    ON
        co.condition_concept_id = d.concept_id
    GROUP BY
        d.skin_condition
),
total_participants AS (
    SELECT
        COUNT(DISTINCT person_id) AS nb_of_participants
    FROM
        `bigquery-public-data.cms_synthetic_patient_data_omop.person`
)
SELECT
    p.skin_condition,
    100 * p.nb_of_participants_with_skin_condition / t.nb_of_participants AS percentage_of_participants
FROM
    participants_with_condition p,
    total_participants t
Database: cms_data (snowflake)
Question: Please tell me the percentage of participants not using quinapril and related medications(Quinapril RxCUI: 35208).
SQL:
WITH quinapril_concept AS (
    SELECT concept_id
    FROM `bigquery-public-data.cms_synthetic_patient_data_omop.concept`
    WHERE concept_code = "35208" AND vocabulary_id = "RxNorm"
),
quinapril_related_medications AS (
    SELECT DISTINCT descendant_concept_id AS concept_id
    FROM `bigquery-public-data.cms_synthetic_patient_data_omop.concept_ancestor`
    WHERE ancestor_concept_id IN (SELECT concept_id FROM quinapril_concept)
),
participants_with_quinapril AS (
    SELECT COUNT(DISTINCT person_id) AS count
    FROM `bigquery-public-data.cms_synthetic_patient_data_omop.drug_exposure`
    WHERE drug_concept_id IN (SELECT concept_id FROM quinapril_related_medications)
),
total_participants AS (
    SELECT COUNT(DISTINCT person_id) AS count
    FROM `bigquery-public-data.cms_synthetic_patient_data_omop.person`
)
SELECT
    100 - (100 * participants_with_quinapril.count / total_participants.count) AS without_quinapril
FROM
    participants_with_quinapril, total_participants
Database: noaa_data (snowflake)
Question: Can you provide the latitude of the final coordinates for the hurricane that traveled the second longest distance in the North Atlantic during 2020?
SQL:
WITH hurricane_geometry AS (
  SELECT
    * EXCEPT (longitude, latitude),
    ST_GEOGPOINT(longitude, latitude) AS geom,
    MAX(usa_wind) OVER (PARTITION BY sid) AS max_wnd_speed
  FROM
    `bigquery-public-data.noaa_hurricanes.hurricanes`
  WHERE
    season = '2020'
    AND basin = 'NA'
    AND name != 'NOT NAMED'
),
dist_between_points AS (
  SELECT
    sid,
    name,
    season,
    iso_time,
    max_wnd_speed,
    geom,
    ST_DISTANCE(geom, LAG(geom, 1) OVER (PARTITION BY sid ORDER BY iso_time ASC)) / 1000 AS dist
  FROM
    hurricane_geometry
),
total_distances AS (
  SELECT
    sid,
    name,
    season,
    iso_time,
    max_wnd_speed,
    geom,
    SUM(dist) OVER (PARTITION BY sid ORDER BY iso_time ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_distance,
    SUM(dist) OVER (PARTITION BY sid) AS total_dist
  FROM
    dist_between_points
),
ranked_hurricanes AS (
  SELECT
    *,
    DENSE_RANK() OVER (ORDER BY total_dist DESC) AS dense_rank
  FROM
    total_distances
)

SELECT
  ST_Y(geom)
FROM
  ranked_hurricanes
WHERE
  dense_rank = 2
ORDER BY
cumulative_distance
DESC
LIMIT 1
;
Database: noaa_data (snowflake)
Question: Please show information about the hurricane with the third longest total travel distance in the North Atlantic during 2020, including its travel coordinates, the cumulative travel distance (in kilometers) at each point, and the maximum sustained wind speed at those times.
SQL:
WITH hurricane_geometry AS (
  SELECT
    * EXCEPT (longitude, latitude),
    ST_GEOGPOINT(longitude, latitude) AS geom,
  FROM
    `bigquery-public-data.noaa_hurricanes.hurricanes`
  WHERE
    season = '2020'
    AND basin = 'NA'
    AND name != 'NOT NAMED'
),
dist_between_points AS (
  SELECT
    sid,
    name,
    season,
    iso_time,
    usa_wind,
    geom,
    ST_DISTANCE(geom, LAG(geom, 1) OVER (PARTITION BY sid ORDER BY iso_time ASC)) / 1000 AS dist
  FROM
    hurricane_geometry
),
total_distances AS (
  SELECT
    sid,
    name,
    season,
    iso_time,
    usa_wind,
    geom,
    SUM(dist) OVER (PARTITION BY sid ORDER BY iso_time ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cumulative_distance,
    SUM(dist) OVER (PARTITION BY sid) AS total_dist
  FROM
    dist_between_points
),
ranked_hurricanes AS (
  SELECT
    *,
    DENSE_RANK() OVER (ORDER BY total_dist DESC) AS dense_rank
  FROM
    total_distances
)

SELECT
  geom,cumulative_distance,usa_wind
FROM
  ranked_hurricanes
WHERE
  dense_rank = 3
ORDER BY
cumulative_distance;
Database: NOAA_DATA_PLUS (snowflake)
Question: Can you provide the count of hurricanes and a list of hurricane names (sorted alphabetically and separated by commas) for each city and its associated zip code, where the hurricanes fall within the boundaries of the zip codes? Please exclude any unnamed hurricanes, and sort the results by the count of hurricanes in descending order. The output should include the following columns: city, zip code, state, count of hurricanes, and the list of hurricanes.
SQL:
Database: NOAA_DATA_PLUS (snowflake)
Question: What are the top 5 zip codes of the areas in the United States that have experienced the most hail storm events in the past 10 years? Don't use data from hail reports table.
SQL:
SELECT
  CONCAT("city", ', ', "state_name") AS "city",
  "zip_code",
  COUNT("event_id") AS "count_storms"
FROM (
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2014
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2015
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2016
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2017
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2018
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2019
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2020
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2021
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2022
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2023
    UNION ALL
    SELECT *
    FROM NOAA_DATA_PLUS.NOAA_HISTORIC_SEVERE_STORMS.STORMS_2024
) AS storms
JOIN NOAA_DATA_PLUS.GEO_US_BOUNDARIES.ZIP_CODES
  ON ST_WITHIN(ST_GEOGFROMWKB(storms."event_point"), ST_GEOGFROMWKB("zip_code_geom"))
WHERE
   LOWER(storms."event_type") = 'hail'
GROUP BY
  "zip_code", 
  "city", 
  "state_name"
ORDER BY
  "count_storms" DESC
LIMIT 5;
Database: noaa_data (snowflake)
Question: Among all NOAA GSOD weather stations that recorded valid daily temperature data (non-missing temp, max, min) in 2019 and whose period of record began on or before January 1, 2000, and continued through at least June 30, 2019, how many of these stations achieved 90% or more of the maximum possible number of valid temperature-record days in 2019?
SQL:
Database: noaa_data (snowflake)
Question: Can you help me retrieve the average temperature, average wind speed, and precipitation for LaGuardia Airport in NYC on June 12 for each year from 2011 through 2020, specifically using the station ID 725030?
SQL:
SELECT
  -- Create a timestamp from the date components.
  TIMESTAMP(CONCAT(year,"-",mo,"-",da)) AS timestamp,
  -- Replace numerical null values with actual null
  AVG(IF (temp=9999.9,
      null,
      temp)) AS temperature,
  AVG(IF (wdsp="999.9",
      null,
      CAST(wdsp AS Float64))) AS wind_speed,
  AVG(IF (prcp=99.99,
      0,
      prcp)) AS precipitation
FROM
  `bigquery-public-data.noaa_gsod.gsod20*`
WHERE
  CAST(YEAR AS INT64) > 2010
  AND CAST(YEAR AS INT64) < 2021
  AND CAST(MO AS INT64) = 6
  AND CAST(DA AS INT64) = 12
  AND stn = "725030" -- La Guardia
GROUP BY
  timestamp
ORDER BY
  timestamp ASC;
Database: noaa_data (snowflake)
Question: What are the top 3 months between 2010 and 2014 with the smallest sum of absolute differences between the average air temperature, wet bulb temperature, dew point temperature, and sea surface temperature, including respective years and sum of differences? Please present the year and month in numerical format.
SQL:
WITH DailyAverages AS (
    SELECT 
        year, month, day,
        air_temperature,
        wetbulb_temperature,
        dewpoint_temperature,
        sea_surface_temp
    FROM 
        `bigquery-public-data.noaa_icoads.icoads_core_*`
    WHERE
        _TABLE_SUFFIX BETWEEN '2010' AND '2014'
),

MonthlyAverages AS (
    SELECT 
        year,
        month,
        AVG(air_temperature) AS avg_air_temperature,
        AVG(wetbulb_temperature) AS avg_wetbulb_temperature,
        AVG(dewpoint_temperature) AS avg_dewpoint_temperature,
        AVG(sea_surface_temp) AS avg_sea_surface_temp
    FROM 
        DailyAverages
    WHERE
        air_temperature IS NOT NULL
        AND wetbulb_temperature IS NOT NULL
        AND dewpoint_temperature IS NOT NULL
        AND sea_surface_temp IS NOT NULL
    GROUP BY 
        year, month
),

DifferenceSums AS (
    SELECT
        year,
        month,
        (ABS(avg_air_temperature - avg_wetbulb_temperature) +
        ABS(avg_air_temperature - avg_dewpoint_temperature) +
        ABS(avg_air_temperature - avg_sea_surface_temp) +
        ABS(avg_wetbulb_temperature - avg_dewpoint_temperature) +
        ABS(avg_wetbulb_temperature - avg_sea_surface_temp) +
        ABS(avg_dewpoint_temperature - avg_sea_surface_temp)) AS sum_of_differences
    FROM 
        MonthlyAverages
)

SELECT
    year,
    month,
    sum_of_differences
FROM
    DifferenceSums
ORDER BY
    sum_of_differences ASC
LIMIT 3;
Database: noaa_data (snowflake)
Question: What are the latitude and longitude coordinates and dates between 2005 and 2015 with the top 5 highest daily average wind speeds, excluding records with missing wind speed values? Using data from tables start with prefix "icoads_core".
SQL:
WITH DailyAverages AS (
    SELECT 
        year, month, day, latitude, longitude,
        AVG(wind_speed) AS avg_wind_speed,
    FROM 
        `bigquery-public-data.noaa_icoads.icoads_core_*`
    WHERE
        _TABLE_SUFFIX BETWEEN '2005' AND '2015'
    GROUP BY 
        year, month, day, latitude, longitude
)
SELECT 
    year, month, day, latitude, longitude,
    avg_wind_speed,

FROM 
    DailyAverages
WHERE
    avg_wind_speed IS NOT NULL

ORDER BY avg_wind_speed DESC LIMIT 5
Database: noaa_data (snowflake)
Question: What percentage of weather stations recorded valid temperature data (with no missing or invalid values) for at least 90% of the days in 2022, where the temperature, maximum, and minimum values are neither NULL nor equal to 9999.9, and the station has a valid identifier (USAF code not equal to '999999'), out of all available stations in the NOAA GSOD database?
SQL:
Database: noaa_data (snowflake)
Question: Which weather stations in Washington State recorded more than 150 rainy days in 2023 but fewer rainy days compared to 2022? Defining a “rainy day” as one having precipitation greater than zero millimeters and not equal to 99.99. Only include stations with valid precipitation data.
SQL:
WITH WashingtonStations2023 AS 
    (
        SELECT 
            weather.stn AS station_id,
            ANY_VALUE(station.name) AS name
        FROM
            `bigquery-public-data.noaa_gsod.stations` AS station
        INNER JOIN
            `bigquery-public-data.noaa_gsod.gsod2023` AS weather
        ON
            station.usaf = weather.stn
        WHERE
            station.state = 'WA' 
            AND 
            station.usaf != '999999'
        GROUP BY
            station_id
    ),
prcp2023 AS (
SELECT
    washington_stations.name,
    (
        SELECT 
            COUNT(*)
        FROM
            `bigquery-public-data.noaa_gsod.gsod2023` AS weather
        WHERE
            washington_stations.station_id = weather.stn
            AND
            prcp > 0
            AND
            prcp !=99.99
    )
    AS rainy_days
FROM 
    WashingtonStations2023 AS washington_stations
ORDER BY
    rainy_days DESC
),
WashingtonStations2022 AS 
    (
        SELECT 
            weather.stn AS station_id,
            ANY_VALUE(station.name) AS name
        FROM
            `bigquery-public-data.noaa_gsod.stations` AS station
        INNER JOIN
            `bigquery-public-data.noaa_gsod.gsod2022` AS weather
        ON
            station.usaf = weather.stn
        WHERE
            station.state = 'WA' 
            AND 
            station.usaf != '999999'
        GROUP BY
            station_id
    ),
prcp2022 AS (
SELECT
    washington_stations.name,
    (
        SELECT 
            COUNT(*)
        FROM
            `bigquery-public-data.noaa_gsod.gsod2022` AS weather
        WHERE
            washington_stations.station_id = weather.stn
            AND
            prcp > 0
            AND
            prcp != 99.99
    )
    AS rainy_days
FROM 
    WashingtonStations2022 AS washington_stations
ORDER BY
    rainy_days DESC
)

SELECT prcp2023.name
FROM prcp2023
JOIN prcp2022
on prcp2023.name = prcp2022.name
WHERE prcp2023.rainy_days > 150
AND prcp2023.rainy_days < prcp2022.rainy_days
Database: NEW_YORK_CITIBIKE_1 (snowflake)
Question: Can you tell me which bike trip in New York City on July 15, 2015, started and ended in ZIP Code areas with the highest average temperature for that day, as recorded by the Central Park weather station (WBAN '94728')? If there's more than one trip that meets these criteria, I'd like to know about the one that starts in the smallest ZIP Code and ends in the largest ZIP Code. Please return the starting and ending ZIP Codes of this trip.
SQL:
SELECT
    "ZIPSTART"."zip_code" AS zip_code_start,
    "ZIPEND"."zip_code" AS zip_code_end
FROM  
    "NEW_YORK_CITIBIKE_1"."NEW_YORK_CITIBIKE"."CITIBIKE_TRIPS" AS "TRI"
INNER JOIN
    "NEW_YORK_CITIBIKE_1"."GEO_US_BOUNDARIES"."ZIP_CODES" AS "ZIPSTART"
    ON ST_WITHIN(
        ST_POINT("TRI"."start_station_longitude", "TRI"."start_station_latitude"),
        ST_GEOGFROMWKB("ZIPSTART"."zip_code_geom")
    )
INNER JOIN
    "NEW_YORK_CITIBIKE_1"."GEO_US_BOUNDARIES"."ZIP_CODES" AS "ZIPEND"
    ON ST_WITHIN(
        ST_POINT("TRI"."end_station_longitude", "TRI"."end_station_latitude"),
        ST_GEOGFROMWKB("ZIPEND"."zip_code_geom")
    )
INNER JOIN
    "NEW_YORK_CITIBIKE_1"."NOAA_GSOD"."GSOD2015" AS "WEA"
    ON TO_DATE(TO_CHAR("WEA"."year") || LPAD(TO_CHAR("WEA"."mo"), 2, '0') || LPAD(TO_CHAR("WEA"."da"), 2, '0'), 'YYYYMMDD') = DATE_TRUNC('DAY', TO_TIMESTAMP_NTZ(TO_NUMBER("TRI"."starttime") / 1000000))
WHERE
    "WEA"."wban" = '94728'
    AND DATE_TRUNC('DAY', TO_TIMESTAMP_NTZ(TO_NUMBER("TRI"."starttime") / 1000000)) = DATE '2015-07-15'
ORDER BY 
    "WEA"."temp" DESC, "ZIPSTART"."zip_code" ASC, "ZIPEND"."zip_code" DESC
LIMIT 1;
Database: noaa_data (snowflake)
Question: Can you calculate the difference in maximum temperature, minimum temperature, and average temperature between US and UK weather stations for each day in October 2023, using the date field, and excluding records with missing or invalid temperature values?
SQL:
with 

stations_selected as (
  select
    usaf,
    wban,
    country,
    name
  from
    `bigquery-public-data.noaa_gsod.stations`
  where
    country in ('US', 'UK')
),

data_filtered as (
  select
    gsod.*,
    stations.country
  from
    `bigquery-public-data.noaa_gsod.gsod2023` gsod
  join
    stations_selected stations
  on
    gsod.stn = stations.usaf
    and gsod.wban = stations.wban
  where
    date(gsod.date) between '2023-10-01' and '2023-10-31'
    and gsod.temp != 9999.9
),

-- US Metrics
us_metrics as (
  select
    date(date) as metric_date,
    avg(temp) as avg_temp_us,
    min(temp) as min_temp_us,
    max(temp) as max_temp_us
  from
    data_filtered
  where
    country = 'US'
  group by
    metric_date
),

-- UK Metrics
uk_metrics as (
  select
    date(date) as metric_date,
    avg(temp) as avg_temp_uk,
    min(temp) as min_temp_uk,
    max(temp) as max_temp_uk
  from
    data_filtered
  where
    country = 'UK'
  group by
    metric_date
),

-- Temperature Differences
temp_differences as (
  select
    us.metric_date,
    us.max_temp_us - uk.max_temp_uk as max_temp_diff,
    us.min_temp_us - uk.min_temp_uk as min_temp_diff,
    us.avg_temp_us - uk.avg_temp_uk as avg_temp_diff
  from
    us_metrics us
  join
    uk_metrics uk
  on
    us.metric_date = uk.metric_date
)

select 
  metric_date, 
  max_temp_diff, 
  min_temp_diff, 
  avg_temp_diff
from 
  temp_differences
order by
  metric_date;
Database: noaa_gsod (snowflake)
Question: What are the top 3 dates in October 2009 with the highest average temperature for station number 723758, in the format YYYY-MM-DD?
SQL:
WITH
  # FIRST CAST EACH YEAR, MONTH, DATE TO STRINGS
  T AS (
    SELECT
      *,
      CAST(year AS STRING) AS year_string,
      CAST(mo AS STRING) AS month_string,
      CAST(da AS STRING) AS day_string
    FROM
      `bigquery-public-data.noaa_gsod.gsod2009`
    WHERE
      stn = "723758"
  ),

  # SECOND, CONCAT ALL THE STRINGS TOGETHER INTO ONE COLUMN
  TT AS (
    SELECT
      *,
      CONCAT(year_string, "-", month_string, "-", day_string) AS date_string
    FROM
      T
  ),

  # THIRD, CAST THE DATE STRING INTO A DATE FORMAT
  TTT AS (
    SELECT
      *,
      CAST(date_string AS DATE) AS date_date
    FROM
      TT
  ),

  # FOURTH, CALCULATE THE MEAN TEMPERATURE FOR EACH DATE
  Temp_Avg AS (
    SELECT
      date_date,
      AVG(temp) AS avg_temp
    FROM
      TTT
    WHERE
      date_date BETWEEN '2009-10-01' AND '2009-10-31'
    GROUP BY
      date_date
  )

# FINAL SELECTION OF TOP 3 DATES WITH HIGHEST MEAN TEMPERATURE
SELECT
  date_date AS dates
FROM
  Temp_Avg
ORDER BY
  avg_temp DESC
LIMIT 3;
Database: new_york_noaa (snowflake)
Question: Could you analyze the relationship between each complaint type and daily temperature in New York City, specifically using temperature data from LaGuardia (STN=725030) and JFK (STN=744860) airports for the 10 years starting in 2008, and then determine, for each complaint type that has more than 5000 total occurrences and shows a strong correlation (absolute value > 0.5) with temperature, the total number of complaints, the total number of days with valid temperature records, and the Pearson correlation coefficients (rounded to four decimals) between temperature and both the daily complaint count as well as the daily percentage of total complaints, excluding any days with missing or invalid temperature data (such as 9999.9)?
SQL:
Database: new_york_noaa (snowflake)
Question: Which complaint types with more than 3000 total requests from 2011 to 2020 show the strongest positive and negative Pearson correlations with the daily average wind speed measured at station 744860 (JFK Airport), based on daily complaint proportions (the ratio of type-specific complaints to total daily complaints)? Please provide the complaint types and their correlation coefficients, rounded to four decimal places.
SQL:
Database: new_york_geo (snowflake)
Question: I want to analyze New York City yellow taxi trip data specifically for January 1, 2015, using the bigquery-public-data.new_york.tlc_yellow_trips_2015 dataset. I need to join this with the geo_us_boundaries.zip_codes table to map each trip to its respective NYC zip code based on the pickup coordinates. The analysis should create a complete hour-by-hour breakdown for all zip codes by cross-joining distinct zip codes with distinct hours, including hours with zero trips. For each zip code and hour combination, calculate the total number of trips and the following time-based metrics: count of trips from 1 hour ago, 1 day (24 hours) ago, 7 days (168 hours) ago, and 14 days (336 hours) ago. Additionally, compute the 14-day and 21-day moving averages and standard deviations of trip counts, excluding the current hour. Only include trips with valid latitude and longitude coordinates. The final results should be sorted by the highest trip counts, showing only the top 5 groups with the most trips.
SQL:
Database: GEO_OPENSTREETMAP (snowflake)
Question: What are the five longest types of highways within the multipolygon boundary of Denmark (as defined by Wikidata ID 'Q35') by total length, analyzed through planet features?
SQL:
WITH bounding_area AS (
    SELECT "geometry" AS geometry
    FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_FEATURES,
    LATERAL FLATTEN(INPUT => planet_features."all_tags") AS "tag"
    WHERE "feature_type" = 'multipolygons'
      AND "tag".value:"key" = 'wikidata'
      AND "tag".value:"value" = 'Q35'
),

highway_info AS (
    SELECT 
        SUM(ST_LENGTH(
                ST_GEOGRAPHYFROMWKB(planet_features."geometry")
            )
        ) AS highway_length,
        "tag".value:"value" AS highway_type
    FROM 
        GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_FEATURES AS planet_features,
        bounding_area
    CROSS JOIN LATERAL FLATTEN(INPUT => planet_features."all_tags") AS "tag"
    WHERE "tag".value:"key" = 'highway'
    AND "feature_type" = 'lines'
    AND ST_DWITHIN(
        ST_GEOGFROMWKB(planet_features."geometry"), 
        ST_GEOGFROMWKB(bounding_area.geometry),
        0.0
    ) 
    GROUP BY highway_type
)

SELECT 
  REPLACE(highway_type, '"', '') AS highway_type
FROM
  highway_info
ORDER BY 
  highway_length DESC
LIMIT 5;
Database: GEO_OPENSTREETMAP (snowflake)
Question: Which OpenStreetMap ID from the planet features table corresponds to an administrative boundary, represented as multipolygons, whose total number of 'amenity'-tagged Points of Interest (POIs), as derived from the planet nodes table, is closest to the median count among all such boundaries?
SQL:
WITH bounding_area AS (
    SELECT 
        "osm_id",
        "geometry" AS geometry,
        ST_AREA(ST_GEOGRAPHYFROMWKB("geometry")) AS area
    FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_FEATURES,
    LATERAL FLATTEN(INPUT => PLANET_FEATURES."all_tags") AS "tag"
    WHERE 
        "feature_type" = 'multipolygons'
        AND "tag".value:"key" = 'boundary'
        AND "tag".value:"value" = 'administrative'
),

poi AS (
    SELECT 
        nodes."id" AS poi_id,
        nodes."geometry" AS poi_geometry,
        tags.value:"value" AS poitype
    FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_NODES AS nodes,
    LATERAL FLATTEN(INPUT => nodes."all_tags") AS tags
    WHERE tags.value:"key" = 'amenity'
),

poi_counts AS (
    SELECT
        ba."osm_id",
        COUNT(poi.poi_id) AS total_pois
    FROM bounding_area ba
    JOIN poi
    ON ST_DWITHIN(
        ST_GEOGRAPHYFROMWKB(ba.geometry), 
        ST_GEOGRAPHYFROMWKB(poi.poi_geometry), 
        0.0
    )
    GROUP BY ba."osm_id"
),

median_value AS (
    SELECT 
        PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY total_pois) AS median_pois
    FROM poi_counts
),

closest_to_median AS (
    SELECT
        "osm_id",
        total_pois,
        ABS(total_pois - (SELECT median_pois FROM median_value)) AS diff_from_median
    FROM poi_counts
)

SELECT
    "osm_id"
FROM closest_to_median
ORDER BY diff_from_median
LIMIT 1;