instance_id,db_id,dialect,question,gold_sql,gold_sql_source,gold_sql_id,gold_columns,n_gold_columns,n_schema_columns,audited,audit_verdict,auto_corrected,lite_instance_id sf001,GLOBAL_WEATHER__CLIMATE_DATA_FOR_BI,snowflake,"Assuming today is April 1, 2024, I would like to know the daily snowfall amounts greater than 6 inches for each U.S. postal code during the week ending after the first two full weeks of the previous year. Show the postal code, date, and snowfall amount.","WITH timestamps AS ( SELECT DATE_TRUNC(year,DATEADD(year,-1,DATE '2024-08-29')) AS ref_timestamp, LAST_DAY(DATEADD(week,2 + CAST(WEEKISO(ref_timestamp) != 1 AS INTEGER),ref_timestamp),week) AS end_week, DATEADD(day, day_num - 7, end_week) AS date_valid_std FROM ( SELECT ROW_NUMBER() OVER (ORDER BY SEQ1()) AS day_num FROM TABLE(GENERATOR(rowcount => 7)) ) ) SELECT country, postal_code, date_valid_std, tot_snowfall_in FROM GLOBAL_WEATHER__CLIMATE_DATA_FOR_BI.standard_tile.history_day NATURAL INNER JOIN timestamps WHERE country='US' AND tot_snowfall_in > 6.0 ORDER BY postal_code,date_valid_std ;",lite,sf001,history_day.country; history_day.date_valid_std; history_day.postal_code; history_day.tot_snowfall_in,4,215,True,ok,False,sf001 sf002,FINANCE__ECONOMICS,snowflake,"As of December 31, 2022, list the top 10 active banks with assets exceeding $10 billion, ranked by the highest percentage of uninsured assets, where the percentage is calculated as one minus the value of the '% Insured (Estimated)' variable from quarterly estimates. Provide the names of these banks and their respective percentages of uninsured assets.","WITH ""FilteredData"" AS ( SELECT ""ID_RSSD""::NUMBER AS ""ID_RSSD_NUM"", ""VARIABLE"", ""VALUE"" FROM ""FINANCE__ECONOMICS"".""CYBERSYN"".""FINANCIAL_INSTITUTION_TIMESERIES"" WHERE ""DATE"" = '2022-12-31' AND ""VARIABLE"" IN ('ASSET', 'ESTINS') ), ""BankFinancials"" AS ( SELECT ""ID_RSSD_NUM"", MAX(CASE WHEN ""VARIABLE"" = 'ASSET' THEN ""VALUE"" END) AS ""TotalAssets"", MAX(CASE WHEN ""VARIABLE"" = 'ESTINS' THEN ""VALUE"" END) AS ""InsuredPercentage"" FROM ""FilteredData"" GROUP BY ""ID_RSSD_NUM"" ) SELECT ""E"".""NAME"", (1 - ""BF"".""InsuredPercentage"") * 100 AS ""Uninsured_Assets_Percentage"" FROM ""FINANCE__ECONOMICS"".""CYBERSYN"".""FINANCIAL_INSTITUTION_ENTITIES"" AS ""E"" JOIN ""BankFinancials"" AS ""BF"" ON ""E"".""ID_RSSD"" = ""BF"".""ID_RSSD_NUM"" WHERE ""E"".""IS_ACTIVE"" = TRUE AND ""BF"".""TotalAssets"" > 10000000000 AND ""BF"".""InsuredPercentage"" IS NOT NULL ORDER BY ""Uninsured_Assets_Percentage"" DESC LIMIT 10;",snow,sf002,financial_institution_entities.id_rssd; financial_institution_entities.is_active; financial_institution_entities.name; financial_institution_timeseries.date; financial_institution_timeseries.id_rssd; financial_institution_timeseries.value; financial_institution_timeseries.variable,7,436,True,ok,False,sf002 sf011,CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE,snowflake,"Determine the population distribution within each block group relative to its census tract in New York State using 2021 ACS data. Include block group ID, census value, state county tract ID, total tract population, and the population ratio of each block group.","WITH BlockGroupAndTractPop AS ( SELECT T1.""BlockGroupID"", T1.""StateCountyTractID"", T2.""CensusValue"" AS ""BlockGroupPopulation"", SUM(T2.""CensusValue"") OVER (PARTITION BY T1.""StateCountyTractID"") AS ""TractPopulation"" FROM ""CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE"".""PUBLIC"".""Dim_CensusGeography"" AS T1 JOIN ""CENSUS_GALAXY__ZIP_CODE_TO_BLOCK_GROUP_SAMPLE"".""PUBLIC"".""Fact_CensusValues_ACS2021"" AS T2 ON T1.""BlockGroupID"" = T2.""BlockGroupID"" WHERE T1.""StateName"" = 'New York' AND T2.""MetricID"" = 'B01003_001E' ) SELECT ""BlockGroupID"", ""BlockGroupPopulation"" AS ""census_value"", ""StateCountyTractID"", ""TractPopulation"" AS ""total_tract_population"", ""BlockGroupPopulation"" / ""TractPopulation"" AS ""population_ratio"" FROM BlockGroupAndTractPop WHERE ""TractPopulation"" > 0",snow,sf011,dim_censusgeography.blockgroupid; dim_censusgeography.statecountytractid; dim_censusgeography.statename; fact_censusvalues_acs2021.blockgroupid; fact_censusvalues_acs2021.censusvalue; fact_censusvalues_acs2021.metricid,6,57,True,ok,False,sf011 sf012,WEATHER__ENVIRONMENT,snowflake,"Using data from the FEMA National Flood Insurance Program Claim Index, for each year from 2010 through 2019, what were the total building damage amounts and total contents damage amounts reported under the National Flood Insurance Program for the NFIP community named 'City Of New York,' grouped by each year of loss?","-- Question: For each loss year from 2010 through 2019, -- return the total building damage amounts and total contents damage amounts -- for NFIP claims where the NFIP community name is exactly 'City Of New York'. -- -- Assumptions / reasoning (per guidelines): -- 1. Use only the FEMA_NATIONAL_FLOOD_INSURANCE_PROGRAM_CLAIM_INDEX table because -- it already contains the required fields (NFIP community name, date of loss, -- building damage amount, contents damage amount). -- 2. Filter exactly on ""NFIP_COMMUNITY_NAME"" = 'City Of New York' (case-sensitive -- equality as in probes) without adding extra communities. -- 3. Limit to years 2010–2019 inclusive via EXTRACT(year FROM ""DATE_OF_LOSS""). -- 4. Aggregate with SUM which automatically ignores NULLs (no additional NULL handling). -- 5. Group by the extracted year and order ascending for readability. SELECT EXTRACT(year FROM ""DATE_OF_LOSS"") AS ""YEAR_OF_LOSS"", SUM(""BUILDING_DAMAGE_AMOUNT"") AS ""total_building_damage_amount"", SUM(""CONTENTS_DAMAGE_AMOUNT"") AS ""total_contents_damage_amount"" FROM ""WEATHER__ENVIRONMENT"".""CYBERSYN"".""FEMA_NATIONAL_FLOOD_INSURANCE_PROGRAM_CLAIM_INDEX"" WHERE ""NFIP_COMMUNITY_NAME"" = 'City Of New York' AND ""DATE_OF_LOSS"" IS NOT NULL AND EXTRACT(year FROM ""DATE_OF_LOSS"") BETWEEN 2010 AND 2019 GROUP BY EXTRACT(year FROM ""DATE_OF_LOSS"") ORDER BY ""YEAR_OF_LOSS"";",snow,sf012,fema_national_flood_insurance_program_claim_index.building_damage_amount; fema_national_flood_insurance_program_claim_index.contents_damage_amount; fema_national_flood_insurance_program_claim_index.date_of_loss; fema_national_flood_insurance_program_claim_index.nfip_community_name,4,313,True,ok,False,sf012 sf014,CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE,snowflake,"What is the New York State ZIP code with the highest number of commuters traveling over one hour, according to 2021 ACS data? Include the zip code, the total commuters, state benchmark for this duration, and state population.","WITH ZipCommuters AS ( SELECT f.""ZipCode"", SUM(f.""CensusValueByZip"") AS ""TotalCommutersOver1Hour"" FROM CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC.""Fact_CensusValues_ACS2021_ByZip"" AS f JOIN CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC.""LU_GeographyExpanded"" AS l ON f.""ZipCode"" = l.""ZipCode"" WHERE l.""PreferredStateAbbrev"" = 'NY' AND f.""MetricID"" IN ('B08303_012E', 'B08303_013E') GROUP BY f.""ZipCode"" ), StateBenchmark AS ( SELECT SUM(""StateBenchmarkValue"") AS ""StateBenchmarkOver1Hour"" FROM CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC.""Fact_StateBenchmark_ACS2021"" WHERE ""StateAbbrev"" = 'NY' AND ""MetricID"" IN ('B08303_012E', 'B08303_013E') ), StatePopulation AS ( SELECT MAX(""TotalStatePopulation"") AS ""StatePopulation"" FROM CENSUS_GALAXY__AIML_MODEL_DATA_ENRICHMENT_SAMPLE.PUBLIC.""Fact_StateBenchmark_ACS2021"" WHERE ""StateAbbrev"" = 'NY' ) SELECT zc.""ZipCode"" AS ""zip_code"", zc.""TotalCommutersOver1Hour"" AS ""total_commuters_over_one_hour"", sb.""StateBenchmarkOver1Hour"" AS ""state_benchmark_for_this_duration"", sp.""StatePopulation"" AS ""state_population"" FROM ZipCommuters zc CROSS JOIN StateBenchmark sb CROSS JOIN StatePopulation sp ORDER BY ""total_commuters_over_one_hour"" DESC LIMIT 1;",snow,sf014,fact_censusvalues_acs2021_byzip.censusvaluebyzip; fact_censusvalues_acs2021_byzip.metricid; fact_censusvalues_acs2021_byzip.zipcode; fact_statebenchmark_acs2021.metricid; fact_statebenchmark_acs2021.stateabbrev; fact_statebenchmark_acs2021.statebenchmarkvalue; fact_statebenchmark_acs2021.totalstatepopulation; lu_geographyexpanded.preferredstateabbrev; lu_geographyexpanded.zipcode,9,57,True,ok,False,sf014 sf018,BRAZE_USER_EVENT_DEMO_DATASET,snowflake,"Examine user engagement with push notifications within a specified one-hour window on June 1, 2023.","WITH all_events AS ( -- SEND events SELECT ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"", COALESCE(""MESSAGE_VARIATION_ID"", ""MESSAGE_VARIATION_API_ID"") AS ""MESSAGE_VARIATION_ID_USED"", ""PLATFORM"", ""AD_TRACKING_ENABLED"", NULL AS ""CARRIER"", NULL AS ""BROWSER"", NULL AS ""DEVICE_MODEL"", 'send' AS event_type FROM BRAZE_USER_EVENT_DEMO_DATASET.PUBLIC.USERS_MESSAGES_PUSHNOTIFICATION_SEND_VIEW WHERE ""TIME"" BETWEEN 1685606400 AND 1685610000 UNION ALL -- BOUNCE events SELECT ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"", COALESCE(""MESSAGE_VARIATION_ID"", ""MESSAGE_VARIATION_API_ID"") AS ""MESSAGE_VARIATION_ID_USED"", ""PLATFORM"", ""AD_TRACKING_ENABLED"", NULL AS ""CARRIER"", NULL AS ""BROWSER"", NULL AS ""DEVICE_MODEL"", 'bounce' AS event_type FROM BRAZE_USER_EVENT_DEMO_DATASET.PUBLIC.USERS_MESSAGES_PUSHNOTIFICATION_BOUNCE_VIEW WHERE ""TIME"" BETWEEN 1685606400 AND 1685610000 UNION ALL -- OPEN events SELECT ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"", COALESCE(""MESSAGE_VARIATION_ID"", ""MESSAGE_VARIATION_API_ID"") AS ""MESSAGE_VARIATION_ID_USED"", ""PLATFORM"", ""AD_TRACKING_ENABLED"", ""CARRIER"", ""BROWSER"", ""DEVICE_MODEL"", 'open' AS event_type FROM BRAZE_USER_EVENT_DEMO_DATASET.PUBLIC.USERS_MESSAGES_PUSHNOTIFICATION_OPEN_VIEW WHERE ""TIME"" BETWEEN 1685606400 AND 1685610000 UNION ALL -- INFLUENCEDOPEN events SELECT ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"", COALESCE(""MESSAGE_VARIATION_ID"", ""MESSAGE_VARIATION_API_ID"") AS ""MESSAGE_VARIATION_ID_USED"", ""PLATFORM"", NULL AS ""AD_TRACKING_ENABLED"", ""CARRIER"", ""BROWSER"", ""DEVICE_MODEL"", 'influenced_open' AS event_type FROM BRAZE_USER_EVENT_DEMO_DATASET.PUBLIC.USERS_MESSAGES_PUSHNOTIFICATION_INFLUENCEDOPEN_VIEW WHERE ""TIME"" BETWEEN 1685606400 AND 1685610000 ) SELECT ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"", ""MESSAGE_VARIATION_ID_USED"" AS ""MESSAGE_VARIATION_ID"", ""PLATFORM"", ""AD_TRACKING_ENABLED"", ""CARRIER"", ""BROWSER"", ""DEVICE_MODEL"", SUM(CASE WHEN event_type = 'send' THEN 1 ELSE 0 END) AS ""push_notification_sends"", COUNT(DISTINCT CASE WHEN event_type = 'send' THEN ""USER_ID"" ELSE NULL END) AS ""unique_push_notification_sends"", SUM(CASE WHEN event_type = 'bounce' THEN 1 ELSE 0 END) AS ""push_notification_bounced"", COUNT(DISTINCT CASE WHEN event_type = 'bounce' THEN ""USER_ID"" ELSE NULL END) AS ""unique_push_notification_bounced"", SUM(CASE WHEN event_type = 'open' THEN 1 ELSE 0 END) AS ""push_notification_open"", COUNT(DISTINCT CASE WHEN event_type = 'open' THEN ""USER_ID"" ELSE NULL END) AS ""unique_push_notification_opened"", SUM(CASE WHEN event_type = 'influenced_open' THEN 1 ELSE 0 END) AS ""push_notification_influenced_open"", COUNT(DISTINCT CASE WHEN event_type = 'influenced_open' THEN ""USER_ID"" ELSE NULL END) AS ""unique_push_notification_influenced_open"" FROM all_events GROUP BY ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"", ""MESSAGE_VARIATION_ID_USED"", ""PLATFORM"", ""AD_TRACKING_ENABLED"", ""CARRIER"", ""BROWSER"", ""DEVICE_MODEL"" ORDER BY ""APP_GROUP_ID"", ""CAMPAIGN_ID"", ""USER_ID"" LIMIT 20",snow,sf018,users_messages_pushnotification_bounce_view.ad_tracking_enabled; users_messages_pushnotification_bounce_view.app_group_id; users_messages_pushnotification_bounce_view.campaign_id; users_messages_pushnotification_bounce_view.message_variation_api_id; users_messages_pushnotification_bounce_view.platform; users_messages_pushnotification_bounce_view.time; users_messages_pushnotification_bounce_view.user_id; users_messages_pushnotification_influencedopen_view.app_group_id; users_messages_pushnotification_influencedopen_view.browser; users_messages_pushnotification_influencedopen_view.campaign_id; users_messages_pushnotification_influencedopen_view.carrier; users_messages_pushnotification_influencedopen_view.device_model; users_messages_pushnotification_influencedopen_view.message_variation_api_id; users_messages_pushnotification_influencedopen_view.message_variation_id; users_messages_pushnotification_influencedopen_view.platform; users_messages_pushnotification_influencedopen_view.time; users_messages_pushnotification_influencedopen_view.user_id; users_messages_pushnotification_open_view.ad_tracking_enabled; users_messages_pushnotification_open_view.app_group_id; users_messages_pushnotification_open_view.browser; users_messages_pushnotification_open_view.campaign_id; users_messages_pushnotification_open_view.carrier; users_messages_pushnotification_open_view.device_model; users_messages_pushnotification_open_view.message_variation_api_id; users_messages_pushnotification_open_view.message_variation_id; users_messages_pushnotification_open_view.platform; users_messages_pushnotification_open_view.time; users_messages_pushnotification_open_view.user_id,28,1780,True,fix,True,sf018 sf040,US_ADDRESSES__POI,snowflake,"Find the top 10 northernmost addresses in Florida's largest zip code area. What are their address numbers, street names, and types?","WITH ""FL_ZIPS"" AS ( SELECT ""RELATED_GEO_ID"" AS ""ZIP_GEO_ID"" FROM ""US_ADDRESSES__POI"".""CYBERSYN"".""GEOGRAPHY_RELATIONSHIPS"" WHERE ""GEO_ID"" = 'geoId/12' AND ""RELATIONSHIP_TYPE"" = 'Contains' AND ""RELATED_LEVEL"" = 'CensusZipCodeTabulationArea' ), ""ZIP_GEOMS"" AS ( SELECT f.""ZIP_GEO_ID"" AS ""GEO_ID"", TO_GEOGRAPHY(c.""VALUE"") AS ""GEOM"" FROM ""FL_ZIPS"" f JOIN ""US_ADDRESSES__POI"".""CYBERSYN"".""GEOGRAPHY_CHARACTERISTICS"" c ON c.""GEO_ID"" = f.""ZIP_GEO_ID"" AND c.""RELATIONSHIP_TYPE"" = 'coordinates_wkt' AND c.""VALUE"" IS NOT NULL ), ""ZIP_AREAS"" AS ( SELECT ""GEO_ID"", ST_AREA(ST_UNION_AGG(""GEOM"")) AS ""AREA_M2"" FROM ""ZIP_GEOMS"" GROUP BY ""GEO_ID"" ), ""LARGEST_FL_ZIP"" AS ( SELECT ""GEO_ID"" AS ""ZIP_GEO_ID"" FROM ""ZIP_AREAS"" ORDER BY ""AREA_M2"" DESC LIMIT 1 ) SELECT a.""NUMBER"" AS ""ADDRESS_NUMBER"", a.""STREET"" AS ""STREET_NAME"", a.""STREET_TYPE"" AS ""STREET_TYPE"" FROM ""US_ADDRESSES__POI"".""CYBERSYN"".""US_ADDRESSES"" a JOIN ""LARGEST_FL_ZIP"" z ON a.""ID_ZIP"" = z.""ZIP_GEO_ID"" WHERE a.""STATE"" = 'FL' AND a.""LATITUDE"" IS NOT NULL AND a.""NUMBER"" IS NOT NULL AND REGEXP_LIKE(a.""NUMBER"", '^[0-9]+$') AND a.""STREET"" IS NOT NULL AND TRIM(a.""STREET"") != '' AND a.""STREET_TYPE"" IS NOT NULL AND TRIM(a.""STREET_TYPE"") != '' ORDER BY a.""LATITUDE"" DESC, a.""LONGITUDE"" DESC LIMIT 10;",snow,sf040,geography_characteristics.geo_id; geography_characteristics.relationship_type; geography_characteristics.value; geography_relationships.geo_id; geography_relationships.related_geo_id; geography_relationships.related_level; geography_relationships.relationship_type; us_addresses.id_zip; us_addresses.latitude; us_addresses.longitude; us_addresses.number; us_addresses.state; us_addresses.street; us_addresses.street_type,14,61,True,ok,False,sf040 sf044,FINANCE__ECONOMICS,snowflake,"What was the percentage change in post-market close prices for the Magnificent 7 tech companies from January 1 to June 30, 2024?","WITH ""tickers"" AS ( SELECT column1 AS ""TICKER"" FROM (VALUES ('AAPL'), ('MSFT'), ('GOOGL'), ('AMZN'), ('NVDA'), ('META'), ('TSLA') ) AS ""v""(column1) ), ""filtered"" AS ( SELECT ""s"".""TICKER"", ""s"".""DATE"", ""s"".""VALUE"" FROM ""FINANCE__ECONOMICS"".""CYBERSYN"".""STOCK_PRICE_TIMESERIES"" AS ""s"" INNER JOIN ""tickers"" AS ""t"" ON ""s"".""TICKER"" = ""t"".""TICKER"" WHERE ""s"".""VARIABLE"" = 'post-market_close' AND ""s"".""DATE"" BETWEEN '2024-01-01' AND '2024-06-30' ), ""start_prices"" AS ( SELECT ""TICKER"", ""DATE"" AS ""START_DATE"", ""VALUE"" AS ""START_VALUE"" FROM ( SELECT ""TICKER"", ""DATE"", ""VALUE"", ROW_NUMBER() OVER (PARTITION BY ""TICKER"" ORDER BY ""DATE"") AS ""RN"" FROM ""filtered"" ) WHERE ""RN"" = 1 ), ""end_prices"" AS ( SELECT ""TICKER"", ""DATE"" AS ""END_DATE"", ""VALUE"" AS ""END_VALUE"" FROM ( SELECT ""TICKER"", ""DATE"", ""VALUE"", ROW_NUMBER() OVER (PARTITION BY ""TICKER"" ORDER BY ""DATE"" DESC) AS ""RN"" FROM ""filtered"" ) WHERE ""RN"" = 1 ), ""split_candidates"" AS ( SELECT ""TICKER"", ""DATE"", ""PREV_VALUE"" / NULLIF(""VALUE"", 0) AS ""RATIO"" FROM ( SELECT ""TICKER"", ""DATE"", ""VALUE"", LAG(""VALUE"") OVER (PARTITION BY ""TICKER"" ORDER BY ""DATE"") AS ""PREV_VALUE"" FROM ""filtered"" ) WHERE ""PREV_VALUE"" IS NOT NULL ), ""split_factors"" AS ( SELECT ""TICKER"", EXP(SUM(LN(ROUND(""RATIO"")))) AS ""TOTAL_FACTOR"" FROM ""split_candidates"" WHERE ""RATIO"" >= 1.5 AND ABS(""RATIO"" - ROUND(""RATIO"")) <= 0.2 GROUP BY ""TICKER"" ) SELECT ""sp"".""TICKER"", ""sp"".""START_DATE"", ""ep"".""END_DATE"", ROUND(""sp"".""START_VALUE"" / COALESCE(""sf"".""TOTAL_FACTOR"", 1), 2) AS ""ADJUSTED_START_PRICE"", ROUND(""ep"".""END_VALUE"", 2) AS ""END_PRICE"", ROUND(((""ep"".""END_VALUE"" - (""sp"".""START_VALUE"" / COALESCE(""sf"".""TOTAL_FACTOR"", 1))) / (""sp"".""START_VALUE"" / COALESCE(""sf"".""TOTAL_FACTOR"", 1))) * 100, 2) AS ""PERCENT_CHANGE"" FROM ""start_prices"" AS ""sp"" INNER JOIN ""end_prices"" AS ""ep"" ON ""sp"".""TICKER"" = ""ep"".""TICKER"" LEFT JOIN ""split_factors"" AS ""sf"" ON ""sp"".""TICKER"" = ""sf"".""TICKER"" ORDER BY ""sp"".""TICKER"";",snow,sf044,stock_price_timeseries.date; stock_price_timeseries.ticker; stock_price_timeseries.value; stock_price_timeseries.variable,4,436,True,fix,False,sf044 sf_bq001,GA360,bigquery,"For each visitor who made at least one transaction in February 2017, how many days elapsed between the date of their first visit in February and the date of their first transaction in February, and on what type of device did they make that first transaction?","DECLARE start_date STRING DEFAULT '20170201'; DECLARE end_date STRING DEFAULT '20170228'; WITH visit AS ( SELECT fullvisitorid, MIN(date) AS date_first_visit FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` WHERE _TABLE_SUFFIX BETWEEN start_date AND end_date GROUP BY fullvisitorid ), transactions AS ( SELECT fullvisitorid, MIN(date) AS date_transactions FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` AS ga, UNNEST(ga.hits) AS hits WHERE hits.transaction.transactionId IS NOT NULL AND _TABLE_SUFFIX BETWEEN start_date AND end_date GROUP BY fullvisitorid ), device_transactions AS ( SELECT DISTINCT fullvisitorid, date, device.deviceCategory FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` AS ga, UNNEST(ga.hits) AS hits WHERE hits.transaction.transactionId IS NOT NULL AND _TABLE_SUFFIX BETWEEN start_date AND end_date ), visits_transactions AS ( SELECT visit.fullvisitorid, date_first_visit, date_transactions, device_transactions.deviceCategory AS device_transaction FROM visit JOIN transactions ON visit.fullvisitorid = transactions.fullvisitorid JOIN device_transactions ON visit.fullvisitorid = device_transactions.fullvisitorid AND transactions.date_transactions = device_transactions.date ) SELECT fullvisitorid, DATE_DIFF(PARSE_DATE('%Y%m%d', date_transactions), PARSE_DATE('%Y%m%d', date_first_visit), DAY) AS time, device_transaction FROM visits_transactions ORDER BY fullvisitorid;",lite,bq001,ga_sessions_*.date; ga_sessions_*.device; ga_sessions_*.fullvisitorid; ga_sessions_*.hits,4,16,True,ok,False,bq001 sf_bq002,GA360,bigquery,"During the first half of 2017, focusing on hits product revenue, which traffic source generated the highest total product revenue, and what were the maximum daily, weekly, and monthly product revenues (in millions) for that top-performing source over this period?","DECLARE start_date STRING DEFAULT '20170101'; DECLARE end_date STRING DEFAULT '20170630'; WITH daily_revenue AS ( SELECT trafficSource.source AS source, date, SUM(productRevenue) / 1000000 AS revenue FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`, UNNEST (hits) AS hits, UNNEST (hits.product) AS product WHERE _table_suffix BETWEEN start_date AND end_date GROUP BY source, date ), weekly_revenue AS ( SELECT source, CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))), 'W', EXTRACT(WEEK FROM (PARSE_DATE('%Y%m%d', date)))) AS week, SUM(revenue) AS revenue FROM daily_revenue GROUP BY source, week ), monthly_revenue AS ( SELECT source, CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))),'0', EXTRACT(MONTH FROM (PARSE_DATE('%Y%m%d', date)))) AS month, SUM(revenue) AS revenue FROM daily_revenue GROUP BY source, month ), top_source AS ( SELECT source, SUM(revenue) AS total_revenue FROM daily_revenue GROUP BY source ORDER BY total_revenue DESC LIMIT 1 ), max_revenues AS ( ( SELECT 'Daily' AS time_type, date AS time, source, MAX(revenue) AS max_revenue FROM daily_revenue WHERE source = (SELECT source FROM top_source) GROUP BY source, date ORDER BY max_revenue DESC LIMIT 1 ) UNION ALL ( SELECT 'Weekly' AS time_type, week AS time, source, MAX(revenue) AS max_revenue FROM weekly_revenue WHERE source = (SELECT source FROM top_source) GROUP BY source, week ORDER BY max_revenue DESC LIMIT 1 ) UNION ALL ( SELECT 'Monthly' AS time_type, month AS time, source, MAX(revenue) AS max_revenue FROM monthly_revenue WHERE source = (SELECT source FROM top_source) GROUP BY source, month ORDER BY max_revenue DESC LIMIT 1 ) ) SELECT max_revenue FROM max_revenues ORDER BY max_revenue DESC; ",lite,bq002,ga_sessions_*.date; ga_sessions_*.hits; ga_sessions_*.trafficsource,3,16,True,ok,False,bq002 sf_bq003,GA360,bigquery,"Between April 1 and July 31 of 2017, using the hits product revenue data along with the totals transactions to classify sessions as purchase (transactions ≥ 1 and productRevenue not null) or non-purchase (transactions null and productRevenue null), compare the average pageviews per visitor for each group by month","WITH cte1 AS ( SELECT CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))), '0', EXTRACT(MONTH FROM (PARSE_DATE('%Y%m%d', date)))) AS month, SUM(totals.pageviews) / COUNT(DISTINCT fullVisitorId) AS avg_pageviews_non_purchase FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST (hits) AS hits, UNNEST (hits.product) AS product WHERE _table_suffix BETWEEN '0401' AND '0731' AND totals.transactions IS NULL AND product.productRevenue IS NULL GROUP BY month ), cte2 AS ( SELECT CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))), '0', EXTRACT(MONTH FROM (PARSE_DATE('%Y%m%d', date)))) AS month, SUM(totals.pageviews) / COUNT(DISTINCT fullVisitorId) AS avg_pageviews_purchase FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST (hits) AS hits, UNNEST (hits.product) AS product WHERE _table_suffix BETWEEN '0401' AND '0731' AND totals.transactions >= 1 AND product.productRevenue IS NOT NULL GROUP BY month ) SELECT month, avg_pageviews_purchase, avg_pageviews_non_purchase FROM cte1 INNER JOIN cte2 USING(month) ORDER BY month;",lite,bq003,ga_sessions_*.date; ga_sessions_*.fullvisitorid; ga_sessions_*.hits; ga_sessions_*.totals,4,16,True,ok,False,bq003 sf_bq004,GA360,bigquery,"In July 2017, among all visitors who bought any YouTube-related product, which distinct product—excluding those containing ‘YouTube’ in the product name—had the highest total quantity purchased?","with product_and_quatity AS ( SELECT DISTINCT v2ProductName AS other_purchased_products, SUM(productQuantity) AS quatity FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST(hits) AS hits, UNNEST(hits.product) AS product WHERE _table_suffix BETWEEN '0701' AND '0731' AND NOT REGEXP_CONTAINS(LOWER(v2ProductName), 'youtube') AND fullVisitorID IN ( SELECT DISTINCT fullVisitorId FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST(hits) AS hits, UNNEST(hits.product) AS product WHERE _table_suffix BETWEEN '0701' AND '0731' AND REGEXP_CONTAINS(LOWER(v2ProductName), 'youtube') ) GROUP BY v2ProductName ) SELECT other_purchased_products FROM product_and_quatity ORDER BY quatity DESC LIMIT 1;",lite,bq004,ga_sessions_*.fullvisitorid; ga_sessions_*.hits,2,16,True,ok,False,bq004 sf_bq006,AUSTIN,bigquery,What is the date with the second highest Z-score for daily counts of 'PUBLIC INTOXICATION' incidents in Austin for the year 2016? List the date in the format of '2016-xx-xx'.,"WITH incident_stats AS ( SELECT COUNT(descript) AS total_pub_intox FROM `bigquery-public-data.austin_incidents.incidents_2016` WHERE descript = 'PUBLIC INTOXICATION' GROUP BY date ), average_and_stddev AS ( SELECT AVG(total_pub_intox) AS avg, STDDEV(total_pub_intox) AS stddev FROM incident_stats ), daily_z_scores AS ( SELECT date, COUNT(descript) AS total_pub_intox, ROUND((COUNT(descript) - a.avg) / a.stddev, 2) AS z_score FROM `bigquery-public-data.austin_incidents.incidents_2016`, (SELECT avg, stddev FROM average_and_stddev) AS a WHERE descript = 'PUBLIC INTOXICATION' GROUP BY date, avg, stddev ) SELECT date FROM daily_z_scores ORDER BY z_score DESC LIMIT 1 OFFSET 1",lite,bq006,incidents_*.date; incidents_*.descript,2,81,True,ok,False,bq006 sf_bq008,GA360,bigquery,"In January 2017, among visitors whose campaign name contains 'Data Share' and who accessed any page starting with '/home', which page did they most commonly visit next, and what is the maximum time (in seconds) they spent on the '/home' page before moving on?","with page_visit_sequence AS ( SELECT fullVisitorID, visitID, pagePath, LEAD(timestamp, 1) OVER (PARTITION BY fullVisitorId, visitID order by timestamp) - timestamp AS page_duration, LEAD(pagePath, 1) OVER (PARTITION BY fullVisitorId, visitID order by timestamp) AS next_page, RANK() OVER (PARTITION BY fullVisitorId, visitID order by timestamp) AS step_number FROM ( SELECT pages.fullVisitorID, pages.visitID, pages.pagePath, visitors.campaign, MIN(pages.timestamp) timestamp FROM ( SELECT fullVisitorId, visitId, trafficSource.campaign campaign FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`, UNNEST(hits) as hits WHERE _TABLE_SUFFIX BETWEEN '20170101' AND '20170131' AND hits.type='PAGE' AND REGEXP_CONTAINS(hits.page.pagePath, r'^/home') AND REGEXP_CONTAINS(trafficSource.campaign, r'Data Share') ) AS visitors JOIN( SELECT fullVisitorId, visitId, visitStartTime + hits.time / 1000 AS timestamp, hits.page.pagePath AS pagePath FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`, UNNEST(hits) as hits WHERE _TABLE_SUFFIX BETWEEN '20170101' AND '20170131' ) as pages ON visitors.fullVisitorID = pages.fullVisitorID AND visitors.visitID = pages.visitID GROUP BY pages.fullVisitorID, visitors.campaign, pages.visitID, pages.pagePath ORDER BY pages.fullVisitorID, pages.visitID, timestamp ) ORDER BY fullVisitorId, visitID, step_number ), most_common_next_page AS ( SELECT next_page, COUNT(next_page) as page_count FROM page_visit_sequence WHERE next_page IS NOT NULL AND REGEXP_CONTAINS(pagePath, r'^/home') GROUP BY next_page ORDER BY page_count DESC LIMIT 1 ), max_page_duration AS ( SELECT MAX(page_duration) as max_duration FROM page_visit_sequence WHERE page_duration IS NOT NULL AND REGEXP_CONTAINS(pagePath, r'^/home') ) SELECT next_page, max_duration FROM most_common_next_page, max_page_duration; ",lite,bq008,ga_sessions_*.fullvisitorid; ga_sessions_*.hits; ga_sessions_*.trafficsource; ga_sessions_*.visitid; ga_sessions_*.visitstarttime,5,16,True,ok,False,bq008 sf_bq009,GA360,bigquery,"Which traffic source has the highest total transaction revenue for the year 2017, and what is the difference in millions (rounded to two decimal places) between the highest and lowest monthly total transaction revenue for that traffic source?","WITH MONTHLY_REVENUE AS ( SELECT FORMAT_DATE(""%Y%m"", PARSE_DATE(""%Y%m%d"", date)) AS month, trafficSource.source AS source, ROUND(SUM(totals.totalTransactionRevenue) / 1000000, 2) AS revenue FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*` GROUP BY 1, 2 ), YEARLY_REVENUE AS ( SELECT source, SUM(revenue) AS total_revenue FROM MONTHLY_REVENUE GROUP BY source ), TOP_SOURCE AS ( SELECT source FROM YEARLY_REVENUE ORDER BY total_revenue DESC LIMIT 1 ), SOURCE_MONTHLY_REVENUE AS ( SELECT month, source, revenue FROM MONTHLY_REVENUE WHERE source IN (SELECT source FROM TOP_SOURCE) ), REVENUE_DIFF AS ( SELECT source, ROUND(MAX(revenue), 2) AS max_revenue, ROUND(MIN(revenue), 2) AS min_revenue, ROUND(MAX(revenue) - MIN(revenue), 2) AS diff_revenue FROM SOURCE_MONTHLY_REVENUE GROUP BY source ) SELECT source, diff_revenue FROM REVENUE_DIFF; ",lite,bq009,ga_sessions_*.date; ga_sessions_*.totals; ga_sessions_*.trafficsource,3,16,True,ok,False,bq009 sf_bq010,GA360,bigquery,"Find the top-selling product among customers who bought 'Youtube Men’s Vintage Henley' in July 2017, excluding itself.","WITH GET_CUS_ID AS ( SELECT DISTINCT fullVisitorId as Henley_CUSTOMER_ID FROM `bigquery-public-data.google_analytics_sample.ga_sessions_201707*`, UNNEST(hits) AS hits, UNNEST(hits.product) as product WHERE product.v2ProductName = ""YouTube Men's Vintage Henley"" AND product.productRevenue IS NOT NULL ) SELECT product.v2ProductName AS other_purchased_products FROM `bigquery-public-data.google_analytics_sample.ga_sessions_201707*` TAB_A RIGHT JOIN GET_CUS_ID ON GET_CUS_ID.Henley_CUSTOMER_ID=TAB_A.fullVisitorId, UNNEST(hits) AS hits, UNNEST(hits.product) as product WHERE TAB_A.fullVisitorId IN ( SELECT * FROM GET_CUS_ID ) AND product.v2ProductName <> ""YouTube Men's Vintage Henley"" AND product.productRevenue IS NOT NULL GROUP BY product.v2ProductName ORDER BY SUM(product.productQuantity) DESC LIMIT 1;",lite,bq010,ga_sessions_*.fullvisitorid; ga_sessions_*.hits,2,16,True,ok,False,bq010 sf_bq011,GA4,bigquery,"How many distinct pseudo users had positive engagement time in the 7-day period ending on January 7, 2021 at 23:59:59, but had no positive engagement time in the 2-day period ending on the same date (January 7, 2021 at 23:59:59) ?","SELECT COUNT(DISTINCT MDaysUsers.user_pseudo_id) AS n_day_inactive_users_count FROM ( SELECT user_pseudo_id FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` AS T CROSS JOIN UNNEST(T.event_params) AS event_params WHERE event_params.key = 'engagement_time_msec' AND event_params.value.int_value > 0 AND event_timestamp > UNIX_MICROS(TIMESTAMP_SUB(TIMESTAMP('2021-01-07 23:59:59'), INTERVAL 7 DAY)) AND _TABLE_SUFFIX BETWEEN '20210101' AND '20210107' ) AS MDaysUsers LEFT JOIN ( SELECT user_pseudo_id FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` AS T CROSS JOIN UNNEST(T.event_params) AS event_params WHERE event_params.key = 'engagement_time_msec' AND event_params.value.int_value > 0 AND event_timestamp > UNIX_MICROS(TIMESTAMP_SUB(TIMESTAMP('2021-01-07 23:59:59'), INTERVAL 2 DAY)) AND _TABLE_SUFFIX BETWEEN '20210105' AND '20210107' ) AS NDaysUsers ON MDaysUsers.user_pseudo_id = NDaysUsers.user_pseudo_id WHERE NDaysUsers.user_pseudo_id IS NULL;",lite,bq011,events_*.event_params; events_*.event_timestamp; events_*.user_pseudo_id,3,23,True,ok,False,bq011 sf_bq012,ETHEREUM_BLOCKCHAIN,snowflake,"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.","WITH tx_fees AS ( SELECT t.""from_address"" AS sender, b.""miner"" AS miner, (t.""receipt_gas_used"" * t.""gas_price"") AS fee FROM ""ETHEREUM_BLOCKCHAIN"".""ETHEREUM_BLOCKCHAIN"".""TRANSACTIONS"" t JOIN ""ETHEREUM_BLOCKCHAIN"".""ETHEREUM_BLOCKCHAIN"".""BLOCKS"" b ON t.""block_hash"" = b.""hash"" WHERE t.""receipt_status"" = 1 ), miner_fee_income AS ( SELECT miner AS address, SUM(fee) AS amount FROM tx_fees WHERE miner IS NOT NULL GROUP BY miner ), sender_fee_deduction AS ( SELECT sender AS address, -SUM(fee) AS amount FROM tx_fees WHERE sender IS NOT NULL GROUP BY sender ), trace_inflows AS ( SELECT tr.""to_address"" AS address, SUM(tr.""value"") AS amount FROM ""ETHEREUM_BLOCKCHAIN"".""ETHEREUM_BLOCKCHAIN"".""TRACES"" tr WHERE tr.""status"" = 1 AND tr.""to_address"" IS NOT NULL AND (tr.""trace_type"" IS NULL OR LOWER(tr.""trace_type"") != 'reward') AND (tr.""call_type"" IS NULL OR LOWER(tr.""call_type"") NOT IN ('delegatecall','callcode','staticcall')) GROUP BY tr.""to_address"" ), trace_outflows AS ( SELECT tr.""from_address"" AS address, -SUM(tr.""value"") AS amount FROM ""ETHEREUM_BLOCKCHAIN"".""ETHEREUM_BLOCKCHAIN"".""TRACES"" tr WHERE tr.""status"" = 1 AND tr.""from_address"" IS NOT NULL AND (tr.""trace_type"" IS NULL OR LOWER(tr.""trace_type"") != 'reward') AND (tr.""call_type"" IS NULL OR LOWER(tr.""call_type"") NOT IN ('delegatecall','callcode','staticcall')) GROUP BY tr.""from_address"" ), all_flows AS ( SELECT address, amount FROM trace_inflows UNION ALL SELECT address, amount FROM trace_outflows UNION ALL SELECT address, amount FROM miner_fee_income UNION ALL SELECT address, amount FROM sender_fee_deduction ), net_balances AS ( SELECT address, SUM(amount) AS net_balance FROM all_flows WHERE address IS NOT NULL GROUP BY address ), top10 AS ( SELECT address, net_balance FROM net_balances ORDER BY net_balance DESC LIMIT 10 ) SELECT ROUND(AVG(net_balance / POWER(10, 15)), 2) AS avg_balance_quadrillions FROM top10;",snow,sf_bq012,blocks.hash; blocks.miner; traces.call_type; traces.from_address; traces.status; traces.to_address; traces.trace_type; traces.value; transactions.block_hash; transactions.from_address; transactions.gas_price; transactions.receipt_gas_used; transactions.receipt_status,13,88,True,fix,False,sf_bq012 sf_bq017,GEO_OPENSTREETMAP,snowflake,"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?","with ""denmark"" as ( select st_collect(to_geography(""PF"".""geometry"")) as ""geom"" from ""GEO_OPENSTREETMAP"".""GEO_OPENSTREETMAP"".""PLANET_FEATURES"" as ""PF"", lateral flatten(input => ""PF"".""all_tags"") as ""TAG"" where ""PF"".""feature_type"" = 'multipolygons' and ""TAG"".""VALUE"":""key""::string = 'wikidata' and ""TAG"".""VALUE"":""value""::string = 'Q35' ), ""highway_lines_raw"" as ( select ""PF"".""osm_id"" as ""osm_id"", ""PF"".""geometry"" as ""geometry"", max(case when ""TAG"".""VALUE"":""key""::string = 'highway' then ""TAG"".""VALUE"":""value""::string end) as ""highway_type"" from ""GEO_OPENSTREETMAP"".""GEO_OPENSTREETMAP"".""PLANET_FEATURES"" as ""PF"", lateral flatten(input => ""PF"".""all_tags"") as ""TAG"" where ""PF"".""feature_type"" = 'lines' group by ""PF"".""osm_id"", ""PF"".""geometry"" having max(case when ""TAG"".""VALUE"":""key""::string = 'highway' then ""TAG"".""VALUE"":""value""::string end) is not null ), ""highway_lines"" as ( select ""osm_id"", to_geography(""geometry"") as ""geom"", ""highway_type"" from ""highway_lines_raw"" ), ""lengths"" as ( select ""HL"".""highway_type"" as ""highway_type"", st_length(st_intersection(""D"".""geom"", ""HL"".""geom"")) as ""length_m"" from ""highway_lines"" as ""HL"" cross join ""denmark"" as ""D"" where st_intersects(""D"".""geom"", ""HL"".""geom"") ) select ""highway_type"", sum(""length_m"") as ""total_length_m"" from ""lengths"" group by ""highway_type"" order by ""total_length_m"" desc limit 5;",snow,sf_bq017,planet_features.all_tags; planet_features.feature_type; planet_features.geometry; planet_features.osm_id,4,86,True,ok,False,sf_bq017 sf_bq018,COVID19_OPEN_DATA,bigquery,Which day in March and April had the highest COVID-19 confirmed case growth rate in the United States? The format is MM-DD.,"WITH us_cases_by_date AS ( SELECT date, SUM( cumulative_confirmed ) AS cases FROM `bigquery-public-data.covid19_open_data.covid19_open_data` WHERE country_name=""United States of America"" AND date between '2020-03-01' and '2020-04-30' GROUP BY date ORDER BY date ASC ) , us_previous_day_comparison AS (SELECT date, cases, LAG(cases) OVER(ORDER BY date) AS previous_day, cases - LAG(cases) OVER(ORDER BY date) AS net_new_cases, (cases - LAG(cases) OVER(ORDER BY date))*100/LAG(cases) OVER(ORDER BY date) AS percentage_increase FROM us_cases_by_date ) SELECT FORMAT_DATE('%m-%d', Date) FROM us_previous_day_comparison ORDER BY percentage_increase DESC LIMIT 1",lite,bq018,covid19_open_data.country_name; covid19_open_data.cumulative_confirmed; covid19_open_data.date,3,701,True,ok,False,bq018 sf_bq021,NEW_YORK,bigquery,"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.","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 ",lite,bq021,citibike_trips.end_station_latitude; citibike_trips.end_station_longitude; citibike_trips.end_station_name; citibike_trips.start_station_latitude; citibike_trips.start_station_longitude; citibike_trips.start_station_name; citibike_trips.starttime; citibike_trips.tripduration; tlc_yellow_trips_*.dropoff_datetime; tlc_yellow_trips_*.dropoff_latitude; tlc_yellow_trips_*.dropoff_longitude; tlc_yellow_trips_*.pickup_datetime; tlc_yellow_trips_*.pickup_latitude; tlc_yellow_trips_*.pickup_longitude,14,275,True,ok,False,bq021 sf_bq022,CHICAGO,bigquery,"Calculate the minimum and maximum trip duration in minutes (rounded to the nearest whole number), total number of trips, and average fare for each of six equal quantile groups based on trip duration, considering only trips between 0 and 60 minutes.","SELECT ROUND(MIN(trip_seconds) / 60, 0) AS min_minutes, ROUND(MAX(trip_seconds) / 60, 0) AS max_minutes, COUNT(*) AS total_trips, AVG(fare) AS average_fare FROM ( SELECT trip_seconds, NTILE(6) OVER (ORDER BY trip_seconds) AS quantile, fare FROM `bigquery-public-data.chicago_taxi_trips.taxi_trips` WHERE trip_seconds BETWEEN 0 AND 3600 ) GROUP BY quantile ORDER BY min_minutes, max_minutes;",lite,bq022,taxi_trips.fare; taxi_trips.trip_seconds,2,45,True,ok,False,bq022 sf_bq025,CENSUS_BUREAU_INTERNATIONAL,bigquery,"Provide a list of the top 10 countries for the year 2020, ordered by the highest percentage of their population under 20 years old. For each country, include the total population under 20 years old, the total midyear population, and the percentage of the population that is under 20 years old.","SELECT age.country_name, SUM(age.population) AS under_25, pop.midyear_population AS total, ROUND((SUM(age.population) / pop.midyear_population) * 100,2) AS pct_under_25 FROM ( SELECT country_name, population, country_code FROM `bigquery-public-data.census_bureau_international.midyear_population_agespecific` WHERE year =2020 AND age < 20) age INNER JOIN ( SELECT midyear_population, country_code FROM `bigquery-public-data.census_bureau_international.midyear_population` WHERE year = 2020) pop ON age.country_code = pop.country_code GROUP BY 1, 3 ORDER BY 4 DESC /* Remove limit for visualization */ LIMIT 10 ",lite,bq025,midyear_population.country_code; midyear_population.midyear_population; midyear_population.year; midyear_population_agespecific.age; midyear_population_agespecific.country_code; midyear_population_agespecific.country_name; midyear_population_agespecific.population; midyear_population_agespecific.year,8,165,True,fix,True,bq025 sf_bq028,DEPS_DEV_V1,snowflake,"Considering only the latest release versions of NPM package, which packages are the top 8 most popular based on the Github star number, as well as their versions?","SELECT q.""package_name"", q.""version"", q.""github_stars"" FROM ( WITH latest_release AS ( SELECT pv.""Name"", pv.""Version"" FROM ""DEPS_DEV_V1"".""DEPS_DEV_V1"".""PACKAGEVERSIONS"" pv WHERE pv.""System"" = 'NPM' AND pv.""Name"" NOT LIKE '%>%' AND COALESCE((pv.""VersionInfo"":""IsRelease"")::BOOLEAN, FALSE) QUALIFY ROW_NUMBER() OVER ( PARTITION BY pv.""Name"" ORDER BY COALESCE(pv.""UpstreamPublishedAt"", pv.""SnapshotAt"") DESC, pv.""Version"" DESC ) = 1 ), latest_project AS ( SELECT pr.""Name"" AS ""ProjectName"", pr.""StarsCount"" FROM ""DEPS_DEV_V1"".""DEPS_DEV_V1"".""PROJECTS"" pr WHERE pr.""Type"" = 'GITHUB' QUALIFY ROW_NUMBER() OVER ( PARTITION BY pr.""Name"" ORDER BY pr.""SnapshotAt"" DESC ) = 1 ), package_project AS ( SELECT DISTINCT pvtp.""Name"", pvtp.""Version"", pvtp.""ProjectName"" FROM ""DEPS_DEV_V1"".""DEPS_DEV_V1"".""PACKAGEVERSIONTOPROJECT"" pvtp WHERE pvtp.""System"" = 'NPM' AND pvtp.""ProjectType"" = 'GITHUB' AND pvtp.""RelationType"" = 'SOURCE_REPO_TYPE' ) SELECT lr.""Name"" AS ""package_name"", lr.""Version"" AS ""version"", lp.""StarsCount"" AS ""github_stars"", ROW_NUMBER() OVER ( PARTITION BY lr.""Name"" ORDER BY lp.""StarsCount"" DESC, mp.""ProjectName"" ) AS rn FROM latest_release lr JOIN package_project mp ON mp.""Name"" = lr.""Name"" AND mp.""Version"" = lr.""Version"" JOIN latest_project lp ON lp.""ProjectName"" = mp.""ProjectName"" ) q WHERE q.rn = 1 ORDER BY q.""github_stars"" DESC, q.""package_name"" LIMIT 8",snow,sf_bq028,packageversions.name; packageversions.snapshotat; packageversions.system; packageversions.upstreampublishedat; packageversions.version; packageversions.versioninfo; packageversiontoproject.name; packageversiontoproject.projectname; packageversiontoproject.projecttype; packageversiontoproject.relationtype; packageversiontoproject.system; packageversiontoproject.version; projects.name; projects.snapshotat; projects.starscount; projects.type,16,78,True,ok,False,sf_bq028 sf_bq031,NOAA_DATA,bigquery,"Provide the daily weather data for Rochester from January 1 to March 31, 2019, including temperature (in Celsius), precipitation (in centimeters), and wind speed (in meters per second). For each variable, calculate the 8-day moving average (including the current day and the previous 7 days). Also, calculate the difference between the moving average on each day and the moving averages for the previous 1 to 8 days (i.e., lag1 to lag8). The result should include: The daily values for temperature, precipitation, and wind speed.The 8-day moving averages for each variable. The differences between the moving averages for each of the previous 1 to 8 days (e.g., the difference between today's moving average and the moving average from 1 day ago, from 2 days ago, and so on). Round all values to one decimal place. The data should be ordered by date, starting from January 9, 2019.","WITH transrate AS ( SELECT DATE(CAST(year AS INT64), CAST(mo AS INT64), CAST(da AS INT64)) AS observation_date , ROUND((temp - 32.0) / 1.8, 1) AS temp_mean_c -- using Celsius instead of Fahrenheit , ROUND(prcp * 2.54, 1) AS prcp_cm -- from inches to centimeters , ROUND(CAST(wdsp AS FLOAT64) * 1.852 / 3.6, 1) AS wdsp_ms -- from knots to meters per second FROM `bigquery-public-data.noaa_gsod.gsod*` WHERE _TABLE_SUFFIX = ""2019"" AND CAST(mo AS INT64) <= 3 AND stn in (SELECT usaf FROM `bigquery-public-data.noaa_gsod.stations` WHERE name = ""ROCHESTER"") ), moving_avg AS ( SELECT observation_date , temp_mean_c , prcp_cm , wdsp_ms , AVG(temp_mean_c) OVER (ORDER BY observation_date ROWS 7 PRECEDING) AS temp_moving_avg , AVG(prcp_cm) OVER (ORDER BY observation_date ROWS 7 PRECEDING) AS prcp_moving_avg , AVG(wdsp_ms) OVER (ORDER BY observation_date ROWS 7 PRECEDING) AS wdsp_moving_avg FROM transrate ), lag_moving_avg AS ( SELECT observation_date , temp_mean_c , prcp_cm , wdsp_ms , LAG(temp_moving_avg, 1) OVER (ORDER BY observation_date) AS lag1_temp_moving_avg , LAG(prcp_moving_avg, 1) OVER (ORDER BY observation_date) AS lag1_prcp_moving_avg , LAG(wdsp_moving_avg, 1) OVER (ORDER BY observation_date) AS lag1_wdsp_moving_avg , LAG(temp_moving_avg, 2) OVER (ORDER BY observation_date) AS lag2_temp_moving_avg , LAG(prcp_moving_avg, 2) OVER (ORDER BY observation_date) AS lag2_prcp_moving_avg , LAG(wdsp_moving_avg, 2) OVER (ORDER BY observation_date) AS lag2_wdsp_moving_avg , LAG(temp_moving_avg, 3) OVER (ORDER BY observation_date) AS lag3_temp_moving_avg , LAG(prcp_moving_avg, 3) OVER (ORDER BY observation_date) AS lag3_prcp_moving_avg , LAG(wdsp_moving_avg, 3) OVER (ORDER BY observation_date) AS lag3_wdsp_moving_avg , LAG(temp_moving_avg, 4) OVER (ORDER BY observation_date) AS lag4_temp_moving_avg , LAG(prcp_moving_avg, 4) OVER (ORDER BY observation_date) AS lag4_prcp_moving_avg , LAG(wdsp_moving_avg, 4) OVER (ORDER BY observation_date) AS lag4_wdsp_moving_avg , LAG(temp_moving_avg, 5) OVER (ORDER BY observation_date) AS lag5_temp_moving_avg , LAG(prcp_moving_avg, 5) OVER (ORDER BY observation_date) AS lag5_prcp_moving_avg , LAG(wdsp_moving_avg, 5) OVER (ORDER BY observation_date) AS lag5_wdsp_moving_avg , LAG(temp_moving_avg, 6) OVER (ORDER BY observation_date) AS lag6_temp_moving_avg , LAG(prcp_moving_avg, 6) OVER (ORDER BY observation_date) AS lag6_prcp_moving_avg , LAG(wdsp_moving_avg, 6) OVER (ORDER BY observation_date) AS lag6_wdsp_moving_avg , LAG(temp_moving_avg, 7) OVER (ORDER BY observation_date) AS lag7_temp_moving_avg , LAG(prcp_moving_avg, 7) OVER (ORDER BY observation_date) AS lag7_prcp_moving_avg , LAG(wdsp_moving_avg, 7) OVER (ORDER BY observation_date) AS lag7_wdsp_moving_avg , LAG(temp_moving_avg, 8) OVER (ORDER BY observation_date) AS lag8_temp_moving_avg , LAG(prcp_moving_avg, 8) OVER (ORDER BY observation_date) AS lag8_prcp_moving_avg , LAG(wdsp_moving_avg, 8) OVER (ORDER BY observation_date) AS lag8_wdsp_moving_avg FROM moving_avg ) SELECT observation_date , temp_mean_c , prcp_cm , wdsp_ms , ROUND(lag1_temp_moving_avg, 1) AS lag1_temp_moving_avg , ROUND(lag1_prcp_moving_avg, 1) AS lag1_prcp_moving_avg , ROUND(lag1_wdsp_moving_avg, 1) AS lag1_wdsp_moving_avg , ROUND(lag1_temp_moving_avg - lag2_temp_moving_avg, 1) AS diff2_temp_moving_avg , ROUND(lag1_prcp_moving_avg - lag2_prcp_moving_avg, 1) AS diff2_prcp_moving_avg , ROUND(lag1_wdsp_moving_avg - lag2_wdsp_moving_avg, 1) AS diff2_wdsp_moving_avg , ROUND(lag2_temp_moving_avg, 1) AS lag2_temp_moving_avg , ROUND(lag2_prcp_moving_avg, 1) AS lag2_prcp_moving_avg , ROUND(lag2_wdsp_moving_avg, 1) AS lag2_wdsp_moving_avg , ROUND(lag2_temp_moving_avg - lag3_temp_moving_avg, 1) AS diff3_temp_moving_avg , ROUND(lag2_prcp_moving_avg - lag3_prcp_moving_avg, 1) AS diff3_prcp_moving_avg , ROUND(lag2_wdsp_moving_avg - lag3_wdsp_moving_avg, 1) AS diff3_wdsp_moving_avg , ROUND(lag3_temp_moving_avg, 1) AS lag3_temp_moving_avg , ROUND(lag3_prcp_moving_avg, 1) AS lag3_prcp_moving_avg , ROUND(lag3_wdsp_moving_avg, 1) AS lag3_wdsp_moving_avg , ROUND(lag3_temp_moving_avg - lag4_temp_moving_avg, 1) AS diff4_temp_moving_avg , ROUND(lag3_prcp_moving_avg - lag4_prcp_moving_avg, 1) AS diff4_prcp_moving_avg , ROUND(lag3_wdsp_moving_avg - lag4_wdsp_moving_avg, 1) AS diff4_wdsp_moving_avg , ROUND(lag4_temp_moving_avg, 1) AS lag4_temp_moving_avg , ROUND(lag4_prcp_moving_avg, 1) AS lag4_prcp_moving_avg , ROUND(lag4_wdsp_moving_avg, 1) AS lag4_wdsp_moving_avg , ROUND(lag4_temp_moving_avg - lag5_temp_moving_avg, 1) AS diff5_temp_moving_avg , ROUND(lag4_prcp_moving_avg - lag5_prcp_moving_avg, 1) AS diff5_prcp_moving_avg , ROUND(lag4_wdsp_moving_avg - lag5_wdsp_moving_avg, 1) AS diff5_wdsp_moving_avg , ROUND(lag5_temp_moving_avg, 1) AS lag5_temp_moving_avg , ROUND(lag5_prcp_moving_avg, 1) AS lag5_prcp_moving_avg , ROUND(lag5_wdsp_moving_avg, 1) AS lag5_wdsp_moving_avg , ROUND(lag5_temp_moving_avg - lag6_temp_moving_avg, 1) AS diff6_temp_moving_avg , ROUND(lag5_prcp_moving_avg - lag6_prcp_moving_avg, 1) AS diff6_prcp_moving_avg , ROUND(lag5_wdsp_moving_avg - lag6_wdsp_moving_avg, 1) AS diff6_wdsp_moving_avg , ROUND(lag6_temp_moving_avg, 1) AS lag6_temp_moving_avg , ROUND(lag6_prcp_moving_avg, 1) AS lag6_prcp_moving_avg , ROUND(lag6_wdsp_moving_avg, 1) AS lag6_wdsp_moving_avg , ROUND(lag6_temp_moving_avg - lag7_temp_moving_avg, 1) AS diff7_temp_moving_avg , ROUND(lag6_prcp_moving_avg - lag7_prcp_moving_avg, 1) AS diff7_prcp_moving_avg , ROUND(lag6_wdsp_moving_avg - lag7_wdsp_moving_avg, 1) AS diff7_wdsp_moving_avg , ROUND(lag7_temp_moving_avg, 1) AS lag7_temp_moving_avg , ROUND(lag7_prcp_moving_avg, 1) AS lag7_prcp_moving_avg , ROUND(lag7_wdsp_moving_avg, 1) AS lag7_wdsp_moving_avg , ROUND(lag7_temp_moving_avg - lag8_temp_moving_avg, 1) AS diff8_temp_moving_avg , ROUND(lag7_prcp_moving_avg - lag8_prcp_moving_avg, 1) AS diff8_prcp_moving_avg , ROUND(lag7_wdsp_moving_avg - lag8_wdsp_moving_avg, 1) AS diff8_wdsp_moving_avg , ROUND(lag8_temp_moving_avg, 1) AS lag8_temp_moving_avg , ROUND(lag8_prcp_moving_avg, 1) AS lag8_prcp_moving_avg , ROUND(lag8_wdsp_moving_avg, 1) AS lag8_wdsp_moving_avg FROM lag_moving_avg WHERE lag8_temp_moving_avg IS NOT NULL ORDER BY observation_date; -- all result rounded to 1 decimal place",lite,bq031,gsod_*.da; gsod_*.mo; gsod_*.prcp; gsod_*.stn; gsod_*.temp; gsod_*.wdsp; gsod_*.year; stations.name; stations.usaf,9,745,True,ok,False,bq031 sf_bq032,NOAA_DATA,bigquery,Can you provide the latitude of the final coordinates for the hurricane that traveled the second longest distance in the North Atlantic during 2020?,"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 ;",lite,bq032,hurricanes.basin; hurricanes.iso_time; hurricanes.latitude; hurricanes.longitude; hurricanes.name; hurricanes.season; hurricanes.sid; hurricanes.usa_wind,8,745,True,ok,False,bq032 sf_bq033,PATENTS,snowflake,"How many U.S. publications related to IoT (where the abstract includes the phrase 'internet of things') were filed each month from 2008 to 2022, including months with no filings?","WITH date_series AS ( SELECT DATE_FROM_PARTS(2008, 1, 1) AS month_start UNION ALL SELECT DATEADD(MONTH, 1, month_start) FROM date_series WHERE month_start < '2022-12-01' ), filtered_data AS ( SELECT TO_CHAR(TRY_TO_DATE(TO_VARCHAR(""filing_date""), 'YYYYMMDD'), 'YYYYMM') AS year_month, ""publication_number"" FROM ""PATENTS"".""PUBLICATIONS"", LATERAL FLATTEN(""abstract_localized"") abs WHERE ""country_code"" = 'US' AND LOWER(abs.value:""text""::STRING) LIKE '%internet of things%' AND ""filing_date"" BETWEEN 20080101 AND 20221231 AND ""filing_date"" != 0 GROUP BY year_month, ""publication_number"" ), monthly_counts AS ( SELECT year_month, COUNT(""publication_number"") AS application_count FROM filtered_data GROUP BY year_month ) SELECT TO_CHAR(ds.month_start, 'YYYYMM') AS ""PATENT_DATE_YEARMONTH"", COALESCE(mc.application_count, 0) AS ""NUMBER_OF_PATENT_APPLICATIONS"" FROM date_series ds LEFT JOIN monthly_counts mc ON TO_CHAR(ds.month_start, 'YYYYMM') = mc.year_month ORDER BY ""PATENT_DATE_YEARMONTH""",snow,sf_bq033,publications.abstract_localized; publications.country_code; publications.filing_date; publications.publication_number,4,79,True,ok,False,sf_bq033 sf_bq034,GHCN_D,bigquery,"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)","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",lite,bq034,ghcnd_stations.id; ghcnd_stations.latitude; ghcnd_stations.longitude; ghcnd_stations.name; ghcnd_stations.state,5,31,True,ok,False,bq034 sf_bq035,SAN_FRANCISCO,bigquery,"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.","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",lite,bq035,bikeshare_stations.latitude; bikeshare_stations.longitude; bikeshare_stations.station_id; bikeshare_trips.bike_number; bikeshare_trips.end_station_id; bikeshare_trips.start_station_id; bikeshare_trips.trip_id,7,118,True,ok,False,bq035 sf_bq037,HUMAN_GENOME_VARIANTS,snowflake,"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'.","WITH min_max AS ( SELECT ""reference_bases"", MIN(""start_position"") as min_start, MAX(""start_position"") as max_start, COUNT(*) as total_count FROM HUMAN_GENOME_VARIANTS.HUMAN_GENOME_VARIANTS._1000_GENOMES_PHASE_3_OPTIMIZED_SCHEMA_VARIANTS_20150220 WHERE ""reference_bases"" IN ('AT', 'TA') GROUP BY ""reference_bases"" ), min_counts AS ( SELECT v.""reference_bases"", v.""start_position"", COUNT(*) as extreme_count FROM HUMAN_GENOME_VARIANTS.HUMAN_GENOME_VARIANTS._1000_GENOMES_PHASE_3_OPTIMIZED_SCHEMA_VARIANTS_20150220 v INNER JOIN min_max mm ON v.""reference_bases"" = mm.""reference_bases"" WHERE v.""start_position"" = mm.min_start GROUP BY v.""reference_bases"", v.""start_position"" ), max_counts AS ( SELECT v.""reference_bases"", v.""start_position"", COUNT(*) as extreme_count FROM HUMAN_GENOME_VARIANTS.HUMAN_GENOME_VARIANTS._1000_GENOMES_PHASE_3_OPTIMIZED_SCHEMA_VARIANTS_20150220 v INNER JOIN min_max mm ON v.""reference_bases"" = mm.""reference_bases"" WHERE v.""start_position"" = mm.max_start GROUP BY v.""reference_bases"", v.""start_position"" ) SELECT mm.""reference_bases"", mm.min_start, mm.max_start, COALESCE(mc.extreme_count, 0) * 1.0 / mm.total_count AS prop_min, COALESCE(mx.extreme_count, 0) * 1.0 / mm.total_count AS prop_max FROM min_max mm LEFT JOIN min_counts mc ON mm.""reference_bases"" = mc.""reference_bases"" LEFT JOIN max_counts mx ON mm.""reference_bases"" = mx.""reference_bases"" ORDER BY mm.""reference_bases"";",snow,sf_bq037,_1000_genomes_phase_3_optimized_schema_variants_20150220.reference_bases; _1000_genomes_phase_3_optimized_schema_variants_20150220.start_position,2,202,True,fix,True,sf_bq037 sf_bq039,NEW_YORK_PLUS,bigquery,"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.","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; ",lite,bq039,taxi_zone_geom.zone_id; taxi_zone_geom.zone_name; tlc_yellow_trips_*.dropoff_datetime; tlc_yellow_trips_*.dropoff_location_id; tlc_yellow_trips_*.fare_amount; tlc_yellow_trips_*.mta_tax; tlc_yellow_trips_*.passenger_count; tlc_yellow_trips_*.pickup_datetime; tlc_yellow_trips_*.pickup_location_id; tlc_yellow_trips_*.tip_amount; tlc_yellow_trips_*.tolls_amount; tlc_yellow_trips_*.total_amount; tlc_yellow_trips_*.trip_distance,13,435,True,ok,False,bq039 sf_bq042,NOAA_DATA,bigquery,"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?","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;",lite,bq042,gsod_*.da; gsod_*.mo; gsod_*.prcp; gsod_*.stn; gsod_*.temp; gsod_*.wdsp; gsod_*.year,7,745,True,fix,False,bq042 sf_bq043,TCGA,snowflake,"What are the RNA expression levels of the genes MDM2, TP53, CDKN1A, and CCNE1, along with associated clinical information, in bladder cancer patients with CDKN2A mutations in the 'TCGA-BLCA' project? Use clinical data from the Genomic Data Commons Release 39, data about somatic mutations derived from the hg19 human genome reference in Feb 2017.","WITH ""cdkn2a_cases"" AS ( SELECT DISTINCT ""case_barcode"" FROM ""TCGA"".""TCGA_VERSIONED"".""SOMATIC_MUTATION_HG19_DCC_2017_02"" WHERE ""project_short_name"" = 'TCGA-BLCA' AND ""Hugo_Symbol"" = 'CDKN2A' AND ""Mutation_Status"" = 'Somatic' UNION SELECT DISTINCT ""case_barcode"" FROM ""TCGA"".""TCGA_VERSIONED"".""SOMATIC_MUTATION_HG19_MC3_2017_02"" WHERE ""project_short_name"" = 'TCGA-BLCA' AND ""Hugo_Symbol"" = 'CDKN2A' ), ""expr_hg19"" AS ( SELECT e.""case_barcode"", MAX(IFF(e.""HGNC_gene_symbol"" = 'MDM2', e.""normalized_count"", NULL)) AS ""MDM2_normalized_count"", MAX(IFF(e.""HGNC_gene_symbol"" = 'TP53', e.""normalized_count"", NULL)) AS ""TP53_normalized_count"", MAX(IFF(e.""HGNC_gene_symbol"" = 'CDKN1A', e.""normalized_count"", NULL)) AS ""CDKN1A_normalized_count"", MAX(IFF(e.""HGNC_gene_symbol"" = 'CCNE1', e.""normalized_count"", NULL)) AS ""CCNE1_normalized_count"" FROM ""TCGA"".""TCGA_VERSIONED"".""RNASEQ_HG19_GDC_2017_02"" e WHERE e.""project_short_name"" = 'TCGA-BLCA' AND e.""HGNC_gene_symbol"" IN ('MDM2','TP53','CDKN1A','CCNE1') AND e.""sample_barcode"" LIKE '%-01%' -- Primary Tumor samples GROUP BY e.""case_barcode"" ) SELECT c.""submitter_id"" AS ""case_barcode"", e.""MDM2_normalized_count"", e.""TP53_normalized_count"", e.""CDKN1A_normalized_count"", e.""CCNE1_normalized_count"", c.""proj__project_id"" AS ""project_id"", c.""primary_site"", c.""disease_type"", c.""demo__gender"" AS ""gender"", c.""demo__race"" AS ""race"", c.""demo__ethnicity"" AS ""ethnicity"", c.""demo__vital_status"" AS ""vital_status"", c.""diag__age_at_diagnosis"" AS ""age_at_diagnosis_days"", c.""diag__year_of_diagnosis"" AS ""year_of_diagnosis"", c.""diag__ajcc_pathologic_stage"" AS ""ajcc_pathologic_stage"", c.""diag__ajcc_clinical_stage"" AS ""ajcc_clinical_stage"" FROM ""TCGA"".""TCGA_VERSIONED"".""CLINICAL_GDC_R39"" c JOIN ""cdkn2a_cases"" m ON c.""submitter_id"" = m.""case_barcode"" LEFT JOIN ""expr_hg19"" e ON e.""case_barcode"" = c.""submitter_id"" WHERE c.""proj__project_id"" = 'TCGA-BLCA' ORDER BY c.""submitter_id"";",snow,sf_bq043,clinical_gdc_r_*.demo__ethnicity; clinical_gdc_r_*.demo__gender; clinical_gdc_r_*.demo__race; clinical_gdc_r_*.demo__vital_status; clinical_gdc_r_*.diag__age_at_diagnosis; clinical_gdc_r_*.diag__ajcc_clinical_stage; clinical_gdc_r_*.diag__ajcc_pathologic_stage; clinical_gdc_r_*.diag__year_of_diagnosis; clinical_gdc_r_*.disease_type; clinical_gdc_r_*.primary_site; clinical_gdc_r_*.proj__project_id; clinical_gdc_r_*.submitter_id; rnaseq_hg19_gdc_2017_02.case_barcode; rnaseq_hg19_gdc_2017_02.hgnc_gene_symbol; rnaseq_hg19_gdc_2017_02.normalized_count; rnaseq_hg19_gdc_2017_02.project_short_name; rnaseq_hg19_gdc_2017_02.sample_barcode; somatic_mutation_hg19_dcc_2017_02.case_barcode; somatic_mutation_hg19_dcc_2017_02.hugo_symbol; somatic_mutation_hg19_dcc_2017_02.mutation_status; somatic_mutation_hg19_dcc_2017_02.project_short_name; somatic_mutation_hg19_mc3_2017_02.case_barcode; somatic_mutation_hg19_mc3_2017_02.hugo_symbol; somatic_mutation_hg19_mc3_2017_02.project_short_name,24,2335,True,ok,False,sf_bq043 sf_bq045,NOAA_DATA,bigquery,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.,"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",lite,bq045,gsod_*.prcp; gsod_*.stn; stations.name; stations.state; stations.usaf,5,745,True,ok,False,bq045 sf_bq049,IOWA_LIQUOR_SALES_PLUS,bigquery,"Please show the monthly per capita Bourbon Whiskey sales during 2022 in Dubuque County for the zip code that ranks third in total Bourbon Whiskey sales, using only the population aged 21 and older.","WITH DUBUQUE_LIQUOR_CTE AS ( SELECT CASE WHEN UPPER(category_name) LIKE 'BUTTERSCOTCH SCHNAPPS' THEN 'All Other' --Edge case is not a scotch WHEN UPPER(category_name) LIKE '%WHISKIES' AND UPPER(category_name) NOT LIKE '%RYE%' AND UPPER(category_name) NOT LIKE '%BOURBON%' AND UPPER(category_name) NOT LIKE '%SCOTCH%' THEN 'Other Whiskey' WHEN UPPER(category_name) LIKE '%RYE%' THEN 'Rye Whiskey' WHEN UPPER(category_name) LIKE '%BOURBON%' THEN 'Bourbon Whiskey' WHEN UPPER(category_name) LIKE '%SCOTCH%' THEN 'Scotch Whiskey' ELSE 'All Other' END AS category_group, EXTRACT(MONTH FROM date) AS month, -- At the time of this query, there is only data until month 6. LEFT(CAST(zip_code AS string),5) AS zip_code, -- Casting to string necessary because zip_code has a mix of int & str types. ROUND(SUM(sale_dollars), 2) AS sale_dollars_sum, FROM bigquery-public-data.iowa_liquor_sales.sales WHERE UPPER(county) = 'DUBUQUE' AND EXTRACT(YEAR FROM date) = 2022 GROUP BY category_group, month, zip_code ORDER BY category_group, month, zip_code ), DUBUQUE_POPULATION_CTE AS ( SELECT zipcode, SUM(population) AS population_sum FROM bigquery-public-data.census_bureau_usa.population_by_zip_2010 WHERE minimum_age >= 21 GROUP BY zipcode ), MONTH_INFO AS ( SELECT l.month, l.zip_code, l.sale_dollars_sum, ROUND(sale_dollars_sum/p.population_sum, 2) AS dollars_per_capita FROM DUBUQUE_LIQUOR_CTE AS l LEFT JOIN DUBUQUE_POPULATION_CTE AS p ON l.zip_code = p.zipcode WHERE category_group = 'Bourbon Whiskey' GROUP BY category_group, zip_code, month, sale_dollars_sum, zipcode, population_sum ORDER BY zip_code, month ), zip_code_sales AS ( SELECT zip_code, SUM(sale_dollars_sum) AS total_sale_dollars_sum FROM MONTH_INFO GROUP BY zip_code ), ranked_zip_codes AS ( SELECT zip_code, total_sale_dollars_sum, ROW_NUMBER() OVER (ORDER BY total_sale_dollars_sum DESC) AS rank FROM zip_code_sales ) SELECT t.month, t.zip_code, t.dollars_per_capita FROM MONTH_INFO t JOIN ranked_zip_codes r ON t.zip_code = r.zip_code WHERE r.rank = 3 ORDER BY t.month;",lite,bq049,population_by_zip_*.minimum_age; population_by_zip_*.population; population_by_zip_*.zipcode; sales.category_name; sales.county; sales.date; sales.sale_dollars; sales.zip_code,8,30,True,ok,False,bq049 sf_bq050,NEW_YORK_CITIBIKE_1,snowflake,"I want to analyze bike trips in New York City for 2014 by linking trip data with weather information to understand how weather conditions (temperature, wind speed, and precipitation) affect bike trips between neighborhoods. For each combination of starting and ending neighborhoods, I need the following: 1. Total number of bike trips between the neighborhoods. 2. Average trip duration in minutes (rounded to 1 decimal). 3. Average temperature at the start of the trip (rounded to 1 decimal). 4. Average wind speed at the start (in meters per second, rounded to 1 decimal). 5. Average precipitation at the start (in centimeters, rounded to 1 decimal). 6. The month with the most trips (e.g., `4` for April). The data should be grouped by the starting and ending neighborhoods, with:`zip_codes` in `geo_us_boundaries` used to map the bike trip locations based on latitude and longitude. `zip_codes` in `cyclistic` used to obtain the borough and neighborhood names. Using weather data from the Central Park station for the trip date, covering all trips in 2014.","WITH ""trips_2014"" AS ( SELECT t.*, TO_TIMESTAMP_NTZ(""starttime"", 6) AS ""start_ts"" FROM ""NEW_YORK_CITIBIKE_1"".""NEW_YORK_CITIBIKE"".""CITIBIKE_TRIPS"" t WHERE YEAR(TO_TIMESTAMP_NTZ(""starttime"", 6)) = 2014 ), ""trip_with_zips"" AS ( SELECT t.*, CAST(szs.""zip_code"" AS NUMBER) AS ""start_zip"", CAST(sze.""zip_code"" AS NUMBER) AS ""end_zip"" FROM ""trips_2014"" t JOIN ""NEW_YORK_CITIBIKE_1"".""GEO_US_BOUNDARIES"".""ZIP_CODES"" szs ON szs.""state_code"" = 'NY' AND ST_WITHIN(ST_POINT(t.""start_station_longitude"", t.""start_station_latitude""), TO_GEOGRAPHY(szs.""zip_code_geom"")) JOIN ""NEW_YORK_CITIBIKE_1"".""GEO_US_BOUNDARIES"".""ZIP_CODES"" sze ON sze.""state_code"" = 'NY' AND ST_WITHIN(ST_POINT(t.""end_station_longitude"", t.""end_station_latitude""), TO_GEOGRAPHY(sze.""zip_code_geom"")) ), ""trip_neighborhoods"" AS ( SELECT twz.*, czs.""borough"" AS ""start_borough"", czs.""neighborhood"" AS ""start_neighborhood"", cze.""borough"" AS ""end_borough"", cze.""neighborhood"" AS ""end_neighborhood"" FROM ""trip_with_zips"" twz JOIN ""NEW_YORK_CITIBIKE_1"".""CYCLISTIC"".""ZIP_CODES"" czs ON czs.""zip"" = twz.""start_zip"" JOIN ""NEW_YORK_CITIBIKE_1"".""CYCLISTIC"".""ZIP_CODES"" cze ON cze.""zip"" = twz.""end_zip"" ), ""weather_central_park"" AS ( SELECT w.""year"", w.""mo"", w.""da"", w.""wban"", NULLIF(w.""temp"", 9999.9) AS ""temp_f"", CAST(NULLIF(w.""wdsp"", '999.9') AS FLOAT) AS ""wdsp_knots"", NULLIF(w.""prcp"", 99.99) AS ""prcp_inches"" FROM ""NEW_YORK_CITIBIKE_1"".""NOAA_GSOD"".""GSOD2014"" w WHERE w.""wban"" = '94728' AND w.""year"" = '2014' ), ""trip_with_weather"" AS ( SELECT tn.*, wc.""temp_f"", wc.""wdsp_knots"", wc.""prcp_inches"" FROM ""trip_neighborhoods"" tn LEFT JOIN ""weather_central_park"" wc ON wc.""mo"" = LPAD(CAST(EXTRACT(MONTH FROM tn.""start_ts"") AS VARCHAR), 2, '0') AND wc.""da"" = LPAD(CAST(EXTRACT(DAY FROM tn.""start_ts"") AS VARCHAR), 2, '0') AND wc.""year"" = '2014' ), ""aggregated"" AS ( SELECT ""start_borough"", ""start_neighborhood"", ""end_borough"", ""end_neighborhood"", COUNT(*) AS ""total_trips"", ROUND(AVG(""tripduration"")/60, 1) AS ""avg_trip_duration_min"", ROUND(AVG(""temp_f""), 1) AS ""avg_temp"", ROUND(AVG(""wdsp_knots"" * 0.514444), 1) AS ""avg_wind_speed_ms"", ROUND(AVG(""prcp_inches"" * 2.54), 1) AS ""avg_precip_cm"" FROM ""trip_with_weather"" GROUP BY ""start_borough"",""start_neighborhood"",""end_borough"",""end_neighborhood"" ), ""monthly_counts"" AS ( SELECT ""start_neighborhood"", ""end_neighborhood"", EXTRACT(MONTH FROM ""start_ts"") AS ""month_num"", COUNT(*) AS ""trips_in_month"" FROM ""trip_with_weather"" GROUP BY ""start_neighborhood"",""end_neighborhood"",EXTRACT(MONTH FROM ""start_ts"") ), ""top_month"" AS ( SELECT ""start_neighborhood"", ""end_neighborhood"", ""month_num"" FROM ( SELECT ""start_neighborhood"", ""end_neighborhood"", ""month_num"", ""trips_in_month"", ROW_NUMBER() OVER ( PARTITION BY ""start_neighborhood"",""end_neighborhood"" ORDER BY ""trips_in_month"" DESC, ""month_num"" ) AS ""rn"" FROM ""monthly_counts"" ) WHERE ""rn"" = 1 ) SELECT a.""start_borough"", a.""start_neighborhood"", a.""end_borough"", a.""end_neighborhood"", a.""total_trips"", a.""avg_trip_duration_min"", a.""avg_temp"", a.""avg_wind_speed_ms"", a.""avg_precip_cm"", tm.""month_num"" AS ""month_with_most_trips"" FROM ""aggregated"" a JOIN ""top_month"" tm ON a.""start_neighborhood"" = tm.""start_neighborhood"" AND a.""end_neighborhood"" = tm.""end_neighborhood"" ORDER BY a.""start_borough"", a.""start_neighborhood"", a.""end_borough"", a.""end_neighborhood"";",snow,sf_bq050,citibike_trips.end_station_latitude; citibike_trips.end_station_longitude; citibike_trips.start_station_latitude; citibike_trips.start_station_longitude; citibike_trips.starttime; citibike_trips.tripduration; gsod_*.da; gsod_*.mo; gsod_*.prcp; gsod_*.temp; gsod_*.wban; gsod_*.wdsp; gsod_*.year; zip_codes.borough; zip_codes.neighborhood; zip_codes.state_code; zip_codes.zip; zip_codes.zip_code; zip_codes.zip_code_geom,19,245,True,ok,False,sf_bq050 sf_bq052,PATENTSVIEW,snowflake,"Retrieve the following information for U.S. patents: The patent ID, title, and application date. The number of backward citations within 1 month before the application date (i.e., patents that cited the current patent before its application). The number of forward citations within 1 month after the application date (i.e., patents that cited the current patent after its application). The abstract text of the patent. Only include patents that belong to specific CPC categories, such as subsection 'C05' or group 'A01G'. The query should filter patents to include only those that have at least one backward citation or one forward citation in the 1-month period specified. Sort the results by application date and return all matching records.","WITH CpcFilteredPatents AS ( SELECT DISTINCT p.""id"", p.""title"", p.""abstract"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""PATENT"" AS p JOIN ""PATENTSVIEW"".""PATENTSVIEW"".""CPC_CURRENT"" AS cpc ON p.""id"" = cpc.""patent_id"" WHERE p.""country"" = 'US' AND (cpc.""subsection_id"" = 'C05' OR cpc.""group_id"" = 'A01G') ) SELECT cfp.""id"" AS patent_id, cfp.""title"", core_app.""date"" AS application_date, COUNT(DISTINCT CASE WHEN citing_app.""date""::DATE >= DATEADD(month, -1, core_app.""date""::DATE) AND citing_app.""date""::DATE < core_app.""date""::DATE THEN usc.""patent_id"" ELSE NULL END) AS num_backward_citations, COUNT(DISTINCT CASE WHEN citing_app.""date""::DATE > core_app.""date""::DATE AND citing_app.""date""::DATE <= DATEADD(month, 1, core_app.""date""::DATE) THEN usc.""patent_id"" ELSE NULL END) AS num_forward_citations, cfp.""abstract"" FROM CpcFilteredPatents AS cfp JOIN ""PATENTSVIEW"".""PATENTSVIEW"".""APPLICATION"" AS core_app ON cfp.""id"" = core_app.""patent_id"" LEFT JOIN ""PATENTSVIEW"".""PATENTSVIEW"".""USPATENTCITATION"" AS usc ON cfp.""id"" = usc.""citation_id"" LEFT JOIN ""PATENTSVIEW"".""PATENTSVIEW"".""APPLICATION"" AS citing_app ON usc.""patent_id"" = citing_app.""patent_id"" GROUP BY cfp.""id"", cfp.""title"", core_app.""date"", cfp.""abstract"" HAVING num_backward_citations > 0 OR num_forward_citations > 0 ORDER BY application_date",snow,sf_bq052,application.date; application.patent_id; cpc_current.group_id; cpc_current.patent_id; cpc_current.subsection_id; patent.abstract; patent.country; patent.id; patent.title; uspatentcitation.citation_id; uspatentcitation.patent_id,11,295,True,fix,True,sf_bq052 sf_bq053,NEW_YORK,bigquery,"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.","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",lite,bq053,tree_census_1995.spc_latin; tree_census_1995.status; tree_census_2015.spc_common; tree_census_2015.spc_latin; tree_census_2015.status; tree_species.fall_color; tree_species.species_scientific_name,7,275,True,fix,True,bq053 sf_bq057,CRYPTO,snowflake,"Which month (e.g., 3 for March) in 2021 witnessed the highest percentage of Bitcoin transaction volume occurring in CoinJoin transactions (defined as transactions with >2 outputs, output value ≤ input value, and having multiple equal-value outputs)? Also provide the percentage of all Bitcoin transactions that were CoinJoins, the percentage of UTXOs involved in CoinJoin transactions (average of input and output percentages), and the percentage of total Bitcoin volume that occurred in CoinJoin transactions for that month. Round all percentages to 1 decimal place.","WITH monthly_transactions AS ( SELECT EXTRACT(MONTH FROM TO_TIMESTAMP(""block_timestamp""/1000000)) as month_num, ""hash"", ""input_count"", ""output_count"", ""input_value"", ""output_value"", ""outputs"" FROM CRYPTO.CRYPTO_BITCOIN.TRANSACTIONS WHERE EXTRACT(YEAR FROM TO_TIMESTAMP(""block_timestamp""/1000000)) = 2021 AND ""is_coinbase"" = FALSE ), potential_coinjoins AS ( SELECT month_num, ""hash"", ""input_count"", ""output_count"", ""input_value"", ""output_value"", ""outputs"" FROM monthly_transactions WHERE ""output_count"" > 2 AND ""output_value"" <= ""input_value"" ), transactions_with_output_values AS ( SELECT t.month_num, t.""hash"", t.""input_count"", t.""output_count"", t.""input_value"", t.""output_value"", output_flat.value:""value""::NUMBER as output_val FROM potential_coinjoins t, LATERAL FLATTEN(input => t.""outputs"") output_flat ), equal_value_groups AS ( SELECT month_num, ""hash"", ""input_count"", ""output_count"", ""input_value"", ""output_value"", output_val, COUNT(*) OVER (PARTITION BY ""hash"", output_val) as same_value_count FROM transactions_with_output_values WHERE output_val > 0 ), coinjoin_transactions AS ( SELECT DISTINCT month_num, ""hash"", ""input_count"", ""output_count"", ""input_value"", ""output_value"" FROM equal_value_groups WHERE same_value_count >= 2 ), monthly_coinjoin_stats AS ( SELECT month_num, COUNT(*) as coinjoin_count, SUM(""input_count"") as total_coinjoin_inputs, SUM(""output_count"") as total_coinjoin_outputs, SUM(""output_value"") as total_coinjoin_volume FROM coinjoin_transactions GROUP BY month_num ), monthly_total_stats AS ( SELECT month_num, COUNT(*) as total_transactions, SUM(""input_count"") as total_inputs, SUM(""output_count"") as total_outputs, SUM(""output_value"") as total_volume FROM monthly_transactions GROUP BY month_num ), monthly_percentages AS ( SELECT t.month_num, COALESCE(c.coinjoin_count, 0) as coinjoin_count, t.total_transactions, COALESCE(c.total_coinjoin_inputs, 0) as total_coinjoin_inputs, COALESCE(c.total_coinjoin_outputs, 0) as total_coinjoin_outputs, t.total_inputs, t.total_outputs, COALESCE(c.total_coinjoin_volume, 0) as total_coinjoin_volume, t.total_volume, ROUND((COALESCE(c.total_coinjoin_volume, 0)::DECIMAL / t.total_volume) * 100, 1) as pct_volume_coinjoin FROM monthly_total_stats t LEFT JOIN monthly_coinjoin_stats c ON t.month_num = c.month_num ), highest_month AS ( SELECT month_num, pct_volume_coinjoin, ROW_NUMBER() OVER (ORDER BY pct_volume_coinjoin DESC) as rank FROM monthly_percentages ) SELECT mp.month_num as month_with_highest_coinjoin_pct, ROUND((mp.coinjoin_count::DECIMAL / mp.total_transactions) * 100, 1) as pct_transactions_coinjoin, ROUND(((mp.total_coinjoin_inputs::DECIMAL / mp.total_inputs) + (mp.total_coinjoin_outputs::DECIMAL / mp.total_outputs)) * 50, 1) as pct_utxos_coinjoin, mp.pct_volume_coinjoin FROM monthly_percentages mp JOIN highest_month hm ON mp.month_num = hm.month_num WHERE hm.rank = 1",snow,sf_bq057,transactions.block_timestamp; transactions.input_count; transactions.input_value; transactions.is_coinbase; transactions.output_count; transactions.output_value; transactions.outputs,7,286,True,fix,True,sf_bq057 sf_bq059,SAN_FRANCISCO_PLUS,bigquery,"What is the highest average speed (rounded to 1 decimal, in metric m/s) for bike trips in Berkeley with trip distance greater than 1000 meters?","WITH stations AS ( SELECT station_id FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_station_info` AS stainfo WHERE stainfo.region_id = ( SELECT region.region_id FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_regions` AS region WHERE region.name = ""Berkeley"" ) ), meta_data AS ( SELECT round(st_distance(start_station_geom, end_station_geom), 1) as distancia_metros, round(st_distance(start_station_geom, end_station_geom) / duration_sec, 1) as velocidade_media FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_trips` AS trips WHERE cast(trips.start_station_id as string) IN (SELECT station_id FROM stations) AND cast(trips.end_station_id as string) IN (SELECT station_id FROM stations) AND start_station_latitude IS NOT NULL AND start_station_longitude IS NOT NULL AND end_station_latitude IS NOT NULL AND end_station_longitude IS NOT NULL AND st_distance(start_station_geom, end_station_geom) > 1000 ORDER BY velocidade_media DESC LIMIT 1 ) SELECT velocidade_media as max_velocity FROM meta_data;",lite,bq059,bikeshare_regions.name; bikeshare_regions.region_id; bikeshare_station_info.region_id; bikeshare_station_info.station_id; bikeshare_trips.duration_sec; bikeshare_trips.end_station_geom; bikeshare_trips.end_station_id; bikeshare_trips.end_station_latitude; bikeshare_trips.end_station_longitude; bikeshare_trips.start_station_geom; bikeshare_trips.start_station_id; bikeshare_trips.start_station_latitude; bikeshare_trips.start_station_longitude,13,556,True,ok,False,bq059 sf_bq060,CENSUS_BUREAU_INTERNATIONAL,bigquery,Which top 3 countries had the highest net migration in 2017 among those with an area greater than 500 square kilometers? And what are their migration rates?,"WITH results AS ( SELECT growth.country_name, growth.net_migration, CAST(area.country_area as INT64) as country_area FROM ( SELECT country_name, net_migration, country_code FROM `bigquery-public-data.census_bureau_international.birth_death_growth_rates` WHERE year = 2017 ) growth INNER JOIN ( SELECT country_area, country_code FROM `bigquery-public-data.census_bureau_international.country_names_area` WHERE country_area > 500 ) area ON growth.country_code = area.country_code ORDER BY net_migration DESC LIMIT 3 ) SELECT country_name, net_migration FROM results;",lite,bq060,birth_death_growth_rates.country_code; birth_death_growth_rates.country_name; birth_death_growth_rates.net_migration; birth_death_growth_rates.year; country_names_area.country_area; country_names_area.country_code,6,165,True,fix,True,bq060 sf_bq061,CENSUS_BUREAU_ACS_1,bigquery,Which census tract has witnessed the largest increase in median income between 2015 and 2018 in California? Tell me the tract code.,"WITH acs_2018 AS ( SELECT geo_id, median_income AS median_income_2018 FROM `bigquery-public-data.census_bureau_acs.censustract_2018_5yr` ), acs_2015 AS ( SELECT geo_id, median_income AS median_income_2015 FROM `bigquery-public-data.census_bureau_acs.censustract_2015_5yr` ), acs_diff AS ( SELECT a18.geo_id, a18.median_income_2018, a15.median_income_2015, (a18.median_income_2018 - a15.median_income_2015) AS median_income_diff, FROM acs_2018 a18 JOIN acs_2015 a15 ON a18.geo_id = a15.geo_id ), max_geo_id AS ( SELECT geo_id FROM acs_diff WHERE median_income_diff IS NOT NULL AND acs_diff.geo_id in ( SELECT geo_id FROM `bigquery-public-data.geo_census_tracts.census_tracts_california` ) ORDER BY median_income_diff DESC LIMIT 1 ) SELECT tracts.tract_ce as tract_code FROM max_geo_id JOIN `bigquery-public-data.geo_census_tracts.census_tracts_california` AS tracts ON max_geo_id.geo_id = tracts.geo_id;",lite,bq061,census_tracts_*.geo_id; census_tracts_*.tract_ce; censustract_*.geo_id; censustract_*.median_income,4,5421,True,ok,False,bq061 sf_bq064,CENSUS_BUREAU_ACS_1,bigquery,"Using the 2017 U.S. Census Tract data from the BigQuery public datasets, you need to proportionally allocate each tract's population and income to the zip codes based on the overlapping area between their geographic boundaries. Then, filter the results to include only those zip codes located within a 5-mile radius of a specific point in Washington State, with coordinates at latitude 47.685833°N and longitude -122.191667°W. Finally, calculate the total population and the average individual income for each zip code (rounded to one decimal place) and sort the results by the average individual income in descending order.","WITH all_zip_tract_join AS ( SELECT zips.zip_code, zips.functional_status as zip_functional_status, tracts.tract_ce, tracts.geo_id as tract_geo_id, tracts.functional_status as tract_functional_status, ST_Area(ST_Intersection(tracts.tract_geom, zips.zip_code_geom)) / ST_Area(tracts.tract_geom) as tract_pct_in_zip_code FROM `bigquery-public-data.geo_census_tracts.us_census_tracts_national` tracts, `bigquery-public-data.geo_us_boundaries.zip_codes` zips WHERE ST_Intersects(tracts.tract_geom, zips.zip_code_geom) ), zip_tract_join AS ( SELECT * FROM all_zip_tract_join WHERE tract_pct_in_zip_code > 0 ), census_totals AS ( -- convert averages to additive totals SELECT geo_id, total_pop, total_pop * income_per_capita AS total_income FROM `bigquery-public-data.census_bureau_acs.censustract_2017_5yr` ), joined AS ( -- join with precomputed census/zip pairs, -- compute zip's share of tract SELECT zip_code, total_pop * tract_pct_in_zip_code AS zip_pop, total_income * tract_pct_in_zip_code AS zip_income FROM census_totals c JOIN zip_tract_join ztj ON c.geo_id = ztj.tract_geo_id ), sums AS ( -- aggregate all ""pieces"" of zip code SELECT zip_code, SUM(zip_pop) AS zip_pop, SUM(zip_income) AS zip_total_inc FROM joined GROUP BY zip_code ), zip_pop_income AS ( SELECT zip_code, zip_pop, -- convert to averages zip_total_inc / zip_pop AS income_per_capita FROM sums ), zipcodes_within_distance as ( SELECT zip_code, zip_code_geom FROM `bigquery-public-data.geo_us_boundaries.zip_codes` WHERE state_code = 'WA' -- Washington state code AND ST_DWithin( ST_GeogPoint(-122.191667, 47.685833), zip_code_geom, 8046.72 ) ) select stats.zip_code, ROUND(stats.zip_pop, 1) as zip_population, ROUND(stats.income_per_capita, 1) as average_income from zipcodes_within_distance area join zip_pop_income stats on area.zip_code = stats.zip_code ORDER BY average_income DESC;",lite,bq064,censustract_*.geo_id; censustract_*.income_per_capita; censustract_*.total_pop; us_census_tracts_national.geo_id; us_census_tracts_national.tract_geom; zip_codes.state_code; zip_codes.zip_code; zip_codes.zip_code_geom,8,5421,True,fix,True,bq064 sf_bq066,SDOH,bigquery,"Could you assess the relationship between the poverty rates from the previous year's census data and the percentage of births without maternal morbidity for the years 2016 to 2018? Use only data for births where no maternal morbidity was reported and for each year, use the 5-year census data from the year before to compute the Pearson correlation coefficient","WITH poverty_and_natality AS ( SELECT EXTRACT(YEAR FROM n.Year) AS data_year, p.geo_id AS county_fips, (p.poverty / p.pop_determined_poverty_status) * 100 AS poverty_rate, SUM(n.Births) AS total_births, SUM(CASE WHEN n.Maternal_Morbidity_YN = 0 THEN n.Births ELSE 0 END) AS births_without_morbidity FROM `bigquery-public-data.census_bureau_acs.county_2015_5yr` p JOIN `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality_by_maternal_morbidity` n ON p.geo_id = n.County_of_Residence_FIPS WHERE p.pop_determined_poverty_status > 0 AND EXTRACT(YEAR FROM n.Year) = 2016 GROUP BY p.geo_id, p.poverty, p.pop_determined_poverty_status, EXTRACT(YEAR FROM n.Year) UNION ALL SELECT EXTRACT(YEAR FROM n.Year) AS data_year, p.geo_id AS county_fips, (p.poverty / p.pop_determined_poverty_status) * 100 AS poverty_rate, SUM(n.Births) AS total_births, SUM(CASE WHEN n.Maternal_Morbidity_YN = 0 THEN n.Births ELSE 0 END) AS births_without_morbidity FROM `bigquery-public-data.census_bureau_acs.county_2016_5yr` p JOIN `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality_by_maternal_morbidity` n ON p.geo_id = n.County_of_Residence_FIPS WHERE p.pop_determined_poverty_status > 0 AND EXTRACT(YEAR FROM n.Year) = 2017 GROUP BY p.geo_id, p.poverty, p.pop_determined_poverty_status, EXTRACT(YEAR FROM n.Year) UNION ALL SELECT EXTRACT(YEAR FROM n.Year) AS data_year, p.geo_id AS county_fips, (p.poverty / p.pop_determined_poverty_status) * 100 AS poverty_rate, SUM(n.Births) AS total_births, SUM(CASE WHEN n.Maternal_Morbidity_YN = 0 THEN n.Births ELSE 0 END) AS births_without_morbidity FROM `bigquery-public-data.census_bureau_acs.county_2017_5yr` p JOIN `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality_by_maternal_morbidity` n ON p.geo_id = n.County_of_Residence_FIPS WHERE p.pop_determined_poverty_status > 0 AND EXTRACT(YEAR FROM n.Year) = 2018 GROUP BY p.geo_id, p.poverty, p.pop_determined_poverty_status, EXTRACT(YEAR FROM n.Year) ) SELECT data_year, CORR(poverty_rate, (births_without_morbidity / total_births) * 100) AS correlation_coefficient FROM poverty_and_natality GROUP BY data_year ",lite,bq066,county_*.births; county_*.county_of_residence_fips; county_*.geo_id; county_*.maternal_morbidity_yn; county_*.pop_determined_poverty_status; county_*.poverty; county_*.year,7,4008,True,ok,False,bq066 sf_bq068,CRYPTO,snowflake,"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?","WITH date_range AS ( SELECT DATE_PART(EPOCH_MICROSECOND, '2014-03-01'::TIMESTAMP) AS start_timestamp, DATE_PART(EPOCH_MICROSECOND, '2014-04-01'::TIMESTAMP) AS end_timestamp ), address_transactions AS ( -- Get all debits (inputs) within the date range SELECT FLATTENED.value::STRING AS address, i.""type"" AS address_type, -i.""value"" AS amount, i.""block_timestamp"" FROM ""CRYPTO"".""CRYPTO_BITCOIN_CASH"".""INPUTS"" i, LATERAL FLATTEN(input => PARSE_JSON(i.""addresses"")) FLATTENED WHERE i.""block_timestamp"" BETWEEN (SELECT start_timestamp FROM date_range) AND (SELECT end_timestamp FROM date_range) UNION ALL -- Get all credits (outputs) within the date range SELECT FLATTENED.value::STRING AS address, o.""type"" AS address_type, o.""value"" AS amount, o.""block_timestamp"" FROM ""CRYPTO"".""CRYPTO_BITCOIN_CASH"".""OUTPUTS"" o, LATERAL FLATTEN(input => PARSE_JSON(o.""addresses"")) FLATTENED WHERE o.""block_timestamp"" BETWEEN (SELECT start_timestamp FROM date_range) AND (SELECT end_timestamp FROM date_range) ), address_balances AS ( SELECT address, address_type, SUM(amount) AS final_balance FROM address_transactions GROUP BY address, address_type ) SELECT address_type, MAX(final_balance) AS max_final_balance, MIN(final_balance) AS min_final_balance FROM address_balances GROUP BY address_type ORDER BY address_type;",snow,sf_bq068,inputs.addresses; inputs.block_timestamp; inputs.type; inputs.value; outputs.addresses; outputs.block_timestamp; outputs.type; outputs.value,8,286,True,fix,False,sf_bq068 sf_bq070,IDC,snowflake,"Could you provide a clean, structured dataset from dicom_all table that only includes SM images marked as VOLUME from the TCGA-LUAD and TCGA-LUSC collections, excluding any slides with compression type “other,” where the specimen preparation step explicitly has “Embedding medium” set to “Tissue freezing medium,” and ensuring that the tissue type is only “normal” or “tumor” and the cancer subtype is reported accordingly?","WITH base AS ( SELECT t.""SOPInstanceUID"", t.""SeriesInstanceUID"", t.""StudyInstanceUID"", t.""PatientID"", t.""collection_id"", t.""collection_name"", t.""Rows"", t.""Columns"", t.""PixelSpacing"", t.""LossyImageCompressionMethod"", t.""VolumetricProperties"", t.""Modality"", t.""gcs_url"", sd.value:""SpecimenIdentifier""::STRING AS SPECIMEN_IDENTIFIER, pams.value:""CodeValue""::STRING AS TISSUE_CODE, pams.value:""CodeMeaning""::STRING AS TISSUE_MEANING FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" t JOIN LATERAL FLATTEN(INPUT => t.""SpecimenDescriptionSequence"") sd JOIN LATERAL FLATTEN(INPUT => sd.value:""PrimaryAnatomicStructureSequence"") pas JOIN LATERAL FLATTEN(INPUT => pas.value:""PrimaryAnatomicStructureModifierSequence"") pams JOIN LATERAL FLATTEN(INPUT => sd.value:""SpecimenPreparationSequence"") sps JOIN LATERAL FLATTEN(INPUT => sps.value:""SpecimenPreparationStepContentItemSequence"") sp JOIN LATERAL FLATTEN(INPUT => sp.value:""ConceptNameCodeSequence"") cn LEFT JOIN LATERAL FLATTEN(INPUT => sp.value:""ConceptCodeSequence"", OUTER => TRUE) cc WHERE t.""Modality"" = 'SM' AND t.""VolumetricProperties"" = 'VOLUME' AND ( t.""collection_name"" IN ('TCGA-LUAD', 'TCGA-LUSC') OR t.""collection_id"" IN ('tcga_luad', 'tcga_lusc') OR t.""tcia_api_collection_id"" IN ('TCGA-LUAD', 'TCGA-LUSC') OR t.""idc_webapp_collection_id"" IN ('TCGA-LUAD', 'TCGA-LUSC') ) AND cn.value:""CodeMeaning""::STRING = 'Embedding medium' AND ( UPPER(COALESCE(sp.value:""TextValue""::STRING, '')) = 'TISSUE FREEZING MEDIUM' OR UPPER(COALESCE(cc.value:""CodeMeaning""::STRING, '')) = 'TISSUE FREEZING MEDIUM' ) AND ( pams.value:""CodeValue""::STRING IN ('17621005', '86049000') OR UPPER(COALESCE(pams.value:""CodeMeaning""::STRING, '')) IN ('NORMAL', 'NEOPLASM', 'TUMOR') ) ), labeled AS ( SELECT DISTINCT b.""SOPInstanceUID"", b.""SeriesInstanceUID"", b.""StudyInstanceUID"", b.""PatientID"", b.""collection_id"", b.""collection_name"", b.""Rows"", b.""Columns"", b.""PixelSpacing"", b.""LossyImageCompressionMethod"", b.""gcs_url"", b.SPECIMEN_IDENTIFIER, CASE WHEN UPPER(COALESCE(b.TISSUE_MEANING, '')) LIKE 'NORMAL%' THEN 'normal' WHEN UPPER(COALESCE(b.TISSUE_MEANING, '')) LIKE '%NEOPLASM%' OR UPPER(COALESCE(b.TISSUE_MEANING, '')) LIKE '%TUMOR%' THEN 'tumor' WHEN b.TISSUE_CODE = '17621005' THEN 'normal' WHEN b.TISSUE_CODE = '86049000' THEN 'tumor' ELSE NULL END AS TISSUE_TYPE, CASE WHEN ARRAY_CONTAINS(TO_VARIANT('ISO_10918_1'), b.""LossyImageCompressionMethod"") THEN 'jpeg' WHEN ARRAY_CONTAINS(TO_VARIANT('ISO_15444_1'), b.""LossyImageCompressionMethod"") THEN 'jpeg2000' ELSE 'other' END AS COMPRESSION_TYPE, CASE WHEN b.""collection_name"" = 'TCGA-LUAD' OR b.""collection_id"" = 'tcga_luad' THEN 'luad' WHEN b.""collection_name"" = 'TCGA-LUSC' OR b.""collection_id"" = 'tcga_lusc' THEN 'lscc' ELSE NULL END AS CANCER_SUBTYPE FROM base b ) SELECT l.""SeriesInstanceUID"" AS ""DIGITAL_SLIDE_ID"", l.""StudyInstanceUID"" AS ""CASE_ID"", l.SPECIMEN_IDENTIFIER AS ""PHYSICAL_SLIDE_ID"", l.""PatientID"" AS ""PATIENT_ID"", l.""collection_id"" AS ""COLLECTION_ID"", l.""SOPInstanceUID"" AS ""INSTANCE_ID"", l.""gcs_url"" AS ""GCS_URL"", l.""Columns"" AS ""WIDTH"", l.""Rows"" AS ""HEIGHT"", ROUND(TRY_TO_DOUBLE((l.""PixelSpacing""[0])::STRING), 4) AS ""PIXEL_SPACING"", l.COMPRESSION_TYPE AS ""COMPRESSION_TYPE"", l.TISSUE_TYPE AS ""TISSUE_TYPE"", l.CANCER_SUBTYPE AS ""CANCER_SUBTYPE"" FROM labeled l WHERE l.COMPRESSION_TYPE IN ('jpeg', 'jpeg2000') AND l.TISSUE_TYPE IN ('normal', 'tumor') ORDER BY l.""SOPInstanceUID"" ASC;",snow,sf_bq070,dicom_all.collection_id; dicom_all.collection_name; dicom_all.columns; dicom_all.gcs_url; dicom_all.idc_webapp_collection_id; dicom_all.lossyimagecompressionmethod; dicom_all.modality; dicom_all.patientid; dicom_all.pixelspacing; dicom_all.rows; dicom_all.seriesinstanceuid; dicom_all.sopinstanceuid; dicom_all.specimendescriptionsequence; dicom_all.studyinstanceuid; dicom_all.tcia_api_collection_id; dicom_all.volumetricproperties,16,2100,True,ok,False,sf_bq070 sf_bq072,DEATH,snowflake,"Please provide, for each age from 12 through 18 (inclusive), the total number of deaths and the number of deaths among individuals identified as Black (based on race descriptions containing the word ‘black’), specifically for deaths associated with ICD-10 codes whose descriptions include the word ‘vehicle’ and for deaths associated with ICD-10 codes whose descriptions include the word ‘firearm.’ Use the EntityAxisConditions table to determine which ICD-10 codes were involved in each death, rather than joining ICD-10 code information directly on the death records.","WITH ""ages"" AS ( SELECT 12 AS ""Age"" UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL SELECT 15 UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL SELECT 18 ), ""vehicle_deaths"" AS ( SELECT DISTINCT ""dr"".""Id"" AS ""dr_id"", ""dr"".""Age"" AS ""Age"", CASE WHEN ""r"".""Description"" ILIKE '%black%' THEN 1 ELSE 0 END AS ""is_black"" FROM ""DEATH"".""DEATH"".""ENTITYAXISCONDITIONS"" AS ""e"" JOIN ""DEATH"".""DEATH"".""ICD10CODE"" AS ""icd"" ON ""icd"".""Code"" = ""e"".""Icd10Code"" JOIN ""DEATH"".""DEATH"".""DEATHRECORDS"" AS ""dr"" ON ""dr"".""Id"" = ""e"".""DeathRecordId"" LEFT JOIN ""DEATH"".""DEATH"".""RACE"" AS ""r"" ON ""r"".""Code"" = ""dr"".""Race"" WHERE ""dr"".""AgeType"" = 1 AND ""dr"".""Age"" BETWEEN 12 AND 18 AND ""icd"".""Description"" ILIKE '%vehicle%' ), ""vehicle_agg"" AS ( SELECT ""Age"", COUNT(DISTINCT ""dr_id"") AS ""vehicle_total_deaths"", COUNT(DISTINCT CASE WHEN ""is_black"" = 1 THEN ""dr_id"" END) AS ""vehicle_black_deaths"" FROM ""vehicle_deaths"" GROUP BY ""Age"" ), ""firearm_deaths"" AS ( SELECT DISTINCT ""dr"".""Id"" AS ""dr_id"", ""dr"".""Age"" AS ""Age"", CASE WHEN ""r"".""Description"" ILIKE '%black%' THEN 1 ELSE 0 END AS ""is_black"" FROM ""DEATH"".""DEATH"".""ENTITYAXISCONDITIONS"" AS ""e"" JOIN ""DEATH"".""DEATH"".""ICD10CODE"" AS ""icd"" ON ""icd"".""Code"" = ""e"".""Icd10Code"" JOIN ""DEATH"".""DEATH"".""DEATHRECORDS"" AS ""dr"" ON ""dr"".""Id"" = ""e"".""DeathRecordId"" LEFT JOIN ""DEATH"".""DEATH"".""RACE"" AS ""r"" ON ""r"".""Code"" = ""dr"".""Race"" WHERE ""dr"".""AgeType"" = 1 AND ""dr"".""Age"" BETWEEN 12 AND 18 AND ""icd"".""Description"" ILIKE '%firearm%' ), ""firearm_agg"" AS ( SELECT ""Age"", COUNT(DISTINCT ""dr_id"") AS ""firearm_total_deaths"", COUNT(DISTINCT CASE WHEN ""is_black"" = 1 THEN ""dr_id"" END) AS ""firearm_black_deaths"" FROM ""firearm_deaths"" GROUP BY ""Age"" ) SELECT ""a"".""Age"", COALESCE(""v"".""vehicle_total_deaths"", 0) AS ""vehicle_total_deaths"", COALESCE(""v"".""vehicle_black_deaths"", 0) AS ""vehicle_black_deaths"", COALESCE(""f"".""firearm_total_deaths"", 0) AS ""firearm_total_deaths"", COALESCE(""f"".""firearm_black_deaths"", 0) AS ""firearm_black_deaths"" FROM ""ages"" AS ""a"" LEFT JOIN ""vehicle_agg"" AS ""v"" ON ""v"".""Age"" = ""a"".""Age"" LEFT JOIN ""firearm_agg"" AS ""f"" ON ""f"".""Age"" = ""a"".""Age"" ORDER BY ""a"".""Age""",snow,sf_bq072,deathrecords.age; deathrecords.agetype; deathrecords.id; deathrecords.race; entityaxisconditions.deathrecordid; entityaxisconditions.icd10code; icd10code.code; icd10code.description; race.code; race.description,10,99,True,ok,False,sf_bq072 sf_bq074,SDOH,bigquery,"Count the number of counties that experienced an increase in unemployment from 2015 to 2018, using 5-year ACS data, and a decrease in dual-eligible enrollee counts between December 1, 2015, and December 1, 2018.","WITH acs_2018 AS ( SELECT geo_id, unemployed_pop AS unemployed_2018 FROM `bigquery-public-data.census_bureau_acs.county_2018_5yr` ), acs_2015 AS ( SELECT geo_id, unemployed_pop AS unemployed_2015 FROM `bigquery-public-data.census_bureau_acs.county_2015_5yr` ), unemployed_change AS ( SELECT u18.unemployed_2018, u18.geo_id, u15.unemployed_2015, (u18.unemployed_2018 - u15.unemployed_2015) AS u_change FROM acs_2018 u18 JOIN acs_2015 u15 ON u18.geo_id = u15.geo_id ), duals_Jan_2018 AS ( SELECT Public_Total AS duals_2018, County_Name, FIPS FROM `bigquery-public-data.sdoh_cms_dual_eligible_enrollment.dual_eligible_enrollment_by_county_and_program` WHERE Date = '2018-12-01' ), duals_Jan_2015 AS ( SELECT Public_Total AS duals_2015, County_Name, FIPS FROM `bigquery-public-data.sdoh_cms_dual_eligible_enrollment.dual_eligible_enrollment_by_county_and_program` WHERE Date = '2015-12-01' ), duals_change AS ( SELECT d18.FIPS, d18.County_Name, d18.duals_2018, d15.duals_2015, (d18.duals_2018 - d15.duals_2015) AS total_duals_diff FROM duals_Jan_2018 d18 JOIN duals_Jan_2015 d15 ON d18.FIPS = d15.FIPS ), corr_tbl AS ( SELECT unemployed_change.geo_id, duals_change.County_Name, unemployed_change.u_change, duals_change.total_duals_diff FROM unemployed_change JOIN duals_change ON unemployed_change.geo_id = duals_change.FIPS ) SELECT COUNT(*) FROM corr_tbl WHERE u_change >0 AND corr_tbl.total_duals_diff < 0",lite,bq074,county_*.geo_id; county_*.unemployed_pop; dual_eligible_enrollment_by_county_and_program.county_name; dual_eligible_enrollment_by_county_and_program.date; dual_eligible_enrollment_by_county_and_program.fips; dual_eligible_enrollment_by_county_and_program.public_total,6,4008,True,ok,False,bq074 sf_bq076,CHICAGO,bigquery,What is the highest number of motor vehicle theft incidents that occurred in any single month during 2016?," SELECT incidents AS highest_monthly_thefts FROM ( SELECT year, EXTRACT(MONTH FROM date) AS month, COUNT(1) AS incidents, RANK() OVER (PARTITION BY year ORDER BY COUNT(1) DESC) AS ranking FROM `bigquery-public-data.chicago_crime.crime` WHERE primary_type = 'MOTOR VEHICLE THEFT' AND year = 2016 GROUP BY year, month ) WHERE ranking = 1 ORDER BY year DESC LIMIT 1;",lite,bq076,crime.date; crime.primary_type; crime.year,3,45,True,ok,False,bq076 sf_bq077,CHICAGO,bigquery,"For each year from 2010 to 2016, what is the highest number of motor thefts in one month?","SELECT year, incidents FROM ( SELECT year, EXTRACT(MONTH FROM date) AS month, COUNT(1) AS incidents, RANK() OVER (PARTITION BY year ORDER BY COUNT(1) DESC) AS ranking FROM `bigquery-public-data.chicago_crime.crime` WHERE primary_type = 'MOTOR VEHICLE THEFT' AND year BETWEEN 2010 AND 2016 GROUP BY year, month ) WHERE ranking = 1 ORDER BY year ASC",lite,bq077,crime.date; crime.primary_type; crime.year,3,45,True,ok,False,bq077 sf_bq078,OPEN_TARGETS_PLATFORM_2,bigquery,Retrieve the approved symbol of target genes with the highest overall score that are associated with the disease 'EFO_0000676' from the data source 'IMPC'.,"SELECT T1.targetId AS target_id, T1.datasourceId, targets.approvedSymbol AS approved_symbol, overall_associations.score AS overall_score FROM `bigquery-public-data.open_targets_platform.associationByDatasourceDirect` as T1 JOIN `bigquery-public-data.open_targets_platform.targets` AS targets ON targetId = targets.id JOIN `bigquery-public-data.open_targets_platform.associationByOverallDirect` AS overall_associations ON T1.targetId = overall_associations.targetId WHERE overall_associations.diseaseId = 'EFO_0000676' AND datasourceId = 'impc' ORDER BY overall_associations.score DESC LIMIT 1; ",lite,bq078,associationbydatasourcedirect.datasourceid; associationbydatasourcedirect.targetid; associationbyoveralldirect.diseaseid; associationbyoveralldirect.score; associationbyoveralldirect.targetid; targets.approvedsymbol; targets.id,7,351,True,ok,False,bq078 sf_bq081,SAN_FRANCISCO_PLUS,bigquery,"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.","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",lite,bq081,bikeshare_regions.name; bikeshare_regions.region_id; bikeshare_station_info.region_id; bikeshare_station_info.station_id; bikeshare_trips.duration_sec; bikeshare_trips.member_gender; bikeshare_trips.start_date; bikeshare_trips.start_station_id; bikeshare_trips.start_station_name; bikeshare_trips.trip_id,10,556,True,ok,False,bq081 sf_bq083,CRYPTO,snowflake,"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.","SELECT TO_DATE(TO_TIMESTAMP_NTZ(""block_timestamp"" / 1000000)) AS ""Date"", TO_CHAR( SUM( (CASE WHEN ""input"" LIKE '0x40c10f19%' THEN 1 ELSE -1 END) * CAST('0x' || LTRIM( SUBSTRING(""input"", CASE WHEN ""input"" LIKE '0x40c10f19%' THEN 75 ELSE 11 END, 64), '0' ) AS FLOAT) / 1000000 ), '$9,999,999,999.00' ) AS ""Δ Total Market Value"" FROM ""CRYPTO"".""CRYPTO_ETHEREUM"".""TRANSACTIONS"" WHERE ""to_address"" = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' AND (""input"" LIKE '0x40c10f19%' OR ""input"" LIKE '0x42966c68%') AND ""block_timestamp"" >= 1672531200000000 AND ""block_timestamp"" < 1704067200000000 GROUP BY ""Date"" ORDER BY ""Date"" DESC;",snow,sf_bq083,transactions.block_timestamp; transactions.input; transactions.to_address,3,286,True,ok,False,sf_bq083 sf_bq085,COVID19_JHU_WORLD_BANK,bigquery,"Could you provide, for the United States, France, China, Italy, Spain, Germany, and Iran, the total number of confirmed COVID-19 cases as of April 20, 2020, along with the number of cases per 100,000 people based on their total 2020 populations calculated by summing all relevant population entries from the World Bank data","SELECT c.country, c.total_confirmed_cases, (c.total_confirmed_cases / p.population) * 100000 AS cases_per_100k FROM ( SELECT CASE WHEN country_region = 'US' THEN 'United States' WHEN country_region = 'Iran' THEN 'Iran, Islamic Rep.' ELSE country_region END AS country, SUM(confirmed) AS total_confirmed_cases FROM `bigquery-public-data.covid19_jhu_csse.summary` WHERE date = '2020-04-20' AND country_region IN ('US', 'France', 'China', 'Italy', 'Spain', 'Germany', 'Iran') GROUP BY country ) AS c JOIN ( SELECT country_name AS country, SUM(value) AS population FROM `bigquery-public-data.world_bank_wdi.indicators_data` WHERE indicator_code = 'SP.POP.TOTL' AND year = 2020 GROUP BY country_name ) AS p ON c.country = p.country ORDER BY cases_per_100k DESC",lite,bq085,indicators_data.country_name; indicators_data.indicator_code; indicators_data.value; indicators_data.year; summary.confirmed; summary.country_region; summary.date,7,3601,True,ok,False,bq085 sf_bq086,COVID19_OPEN_WORLD_BANK,bigquery,"You need to calculate the percentage of each country's population that had been confirmed with COVID-19 by June 30, 2020. The population data for 2018 can be found in the World Bank dataset, and the cumulative COVID-19 confirmed cases data is available in the COVID-19 Open Data dataset. Calculate the percentage of each country's population, that was cumulatively confirmed to have COVID-19","WITH country_pop AS ( SELECT country_code AS iso_3166_1_alpha_3, year_2018 AS population_2018 FROM `bigquery-public-data.world_bank_global_population.population_by_country`) SELECT country_code, country_name, cumulative_confirmed AS june_confirmed_cases, population_2018, ROUND(cumulative_confirmed/population_2018 * 100,2) AS case_percent FROM `bigquery-public-data.covid19_open_data.covid19_open_data` JOIN country_pop USING (iso_3166_1_alpha_3) WHERE date = '2020-06-30' AND aggregation_level = 0 ORDER BY case_percent DESC",lite,bq086,covid19_open_data.aggregation_level; covid19_open_data.country_code; covid19_open_data.country_name; covid19_open_data.cumulative_confirmed; covid19_open_data.date; covid19_open_data.iso_3166_1_alpha_3; population_by_country.country_code; population_by_country.year_2018,8,845,True,fix,True,bq086 sf_bq087,COVID19_SYMPTOM_SEARCH,bigquery,"Please calculate the overall percentage change in the average weekly search frequency for the symptom 'Anosmia' across the five New York City counties—Bronx County, Queens County, Kings County, New York County, and Richmond County—by comparing the combined data from January 1, 2019, through December 31, 2019, with the combined data from January 1, 2020, through December 31, 2020.","SELECT table_2019.avg_symptom_Anosmia_2019, table_2020.avg_symptom_Anosmia_2020, ((table_2020.avg_symptom_Anosmia_2020 - table_2019.avg_symptom_Anosmia_2019) / table_2019.avg_symptom_Anosmia_2019) * 100 AS avg_increase FROM ( SELECT AVG(SAFE_CAST(symptom_Anosmia AS FLOAT64)) AS avg_symptom_Anosmia_2020 FROM `bigquery-public-data.covid19_symptom_search.symptom_search_sub_region_2_weekly` WHERE sub_region_1 = ""New York"" AND sub_region_2 IN (""Bronx County"", ""Queens County"", ""Kings County"", ""New York County"", ""Richmond County"") AND date >= '2020-01-01' AND date < '2021-01-01' ) AS table_2020, ( SELECT AVG(SAFE_CAST(symptom_Anosmia AS FLOAT64)) AS avg_symptom_Anosmia_2019 FROM `bigquery-public-data.covid19_symptom_search.symptom_search_sub_region_2_weekly` WHERE sub_region_1 = ""New York"" AND sub_region_2 IN (""Bronx County"", ""Queens County"", ""Kings County"", ""New York County"", ""Richmond County"") AND date >= '2019-01-01' AND date < '2020-01-01' ) AS table_2019 ",lite,bq087,symptom_search_*.date; symptom_search_*.sub_region_1; symptom_search_*.sub_region_2; symptom_search_*.symptom_anosmia,4,860,True,ok,False,bq087 sf_bq088,COVID19_SYMPTOM_SEARCH,bigquery,"Please calculate the average levels of anxiety and depression symptoms from the weekly country data for the United States during the periods from January 1, 2019, to January 1, 2020, and from January 1, 2020, to January 1, 2021. Then, compute the percentage increase in these average symptom levels from the 2019 period to the 2020 period.","SELECT table_2019.avg_symptom_Anxiety_2019, table_2020.avg_symptom_Anxiety_2020, ((table_2020.avg_symptom_Anxiety_2020 - table_2019.avg_symptom_Anxiety_2019)/table_2019.avg_symptom_Anxiety_2019) * 100 AS percent_increase_anxiety, table_2019.avg_symptom_Depression_2019, table_2020.avg_symptom_Depression_2020, ((table_2020.avg_symptom_Depression_2020 - table_2019.avg_symptom_Depression_2019)/table_2019.avg_symptom_Depression_2019) * 100 AS percent_increase_depression FROM ( SELECT AVG(CAST(symptom_Anxiety AS FLOAT64)) AS avg_symptom_Anxiety_2020, AVG(CAST(symptom_Depression AS FLOAT64)) AS avg_symptom_Depression_2020, FROM `bigquery-public-data.covid19_symptom_search.symptom_search_country_weekly` WHERE country_region_code = ""US"" AND date >= '2020-01-01' AND date <'2021-01-01') AS table_2020, ( SELECT AVG(CAST(symptom_Anxiety AS FLOAT64)) AS avg_symptom_Anxiety_2019, AVG(CAST(symptom_Depression AS FLOAT64)) AS avg_symptom_Depression_2019, FROM `bigquery-public-data.covid19_symptom_search.symptom_search_country_weekly` WHERE country_region_code = ""US"" AND date >= '2019-01-01' AND date <'2020-01-01') AS table_2019",lite,bq088,symptom_search_*.country_region_code; symptom_search_*.date; symptom_search_*.symptom_anxiety; symptom_search_*.symptom_depression,4,860,True,ok,False,bq088 sf_bq089,COVID19_USA,bigquery,"Given the latest population estimates from the 2018 five-year American Community Survey, what is the number of vaccine sites per 1000 people for counties in California?","WITH num_vaccine_sites_per_county AS ( SELECT facility_sub_region_1 AS us_state, facility_sub_region_2 AS us_county, facility_sub_region_2_code AS us_county_fips, COUNT(DISTINCT facility_place_id) AS num_vaccine_sites FROM bigquery-public-data.covid19_vaccination_access.facility_boundary_us_all WHERE STARTS_WITH(facility_sub_region_2_code, ""06"") GROUP BY facility_sub_region_1, facility_sub_region_2, facility_sub_region_2_code ), total_population_per_county AS ( SELECT LEFT(geo_id, 5) AS us_county_fips, ROUND(SUM(total_pop)) AS total_population FROM bigquery-public-data.census_bureau_acs.censustract_2018_5yr WHERE STARTS_WITH(LEFT(geo_id, 5), ""06"") GROUP BY LEFT(geo_id, 5) ) SELECT * EXCEPT(us_county_fips), ROUND((num_vaccine_sites * 1000) / total_population, 2) AS sites_per_1k_ppl FROM num_vaccine_sites_per_county INNER JOIN total_population_per_county USING (us_county_fips) ORDER BY sites_per_1k_ppl ASC LIMIT 100;",lite,bq089,censustract_*.geo_id; censustract_*.total_pop; facility_boundary_us_*.facility_place_id; facility_boundary_us_*.facility_sub_region_1; facility_boundary_us_*.facility_sub_region_2; facility_boundary_us_*.facility_sub_region_2_code,6,6021,True,ok,False,bq089 sf_bq090,CYMBAL_INVESTMENTS,bigquery,How much higher the average intrinsic value is for trades using the feeling-lucky strategy compared to those using the momentum strategy under long-side trades?,"WITH MomentumTrades AS ( SELECT StrikePrice - LastPx AS priceDifference FROM `bigquery-public-data.cymbal_investments.trade_capture_report` WHERE SUBSTR(TargetCompID, 0, 4) = 'MOMO' AND (SELECT Side FROM UNNEST(Sides)) = 'LONG' ), FeelingLuckyTrades AS ( SELECT StrikePrice - LastPx AS priceDifference FROM `bigquery-public-data.cymbal_investments.trade_capture_report` WHERE SUBSTR(TargetCompID, 0, 4) = 'LUCK' AND (SELECT Side FROM UNNEST(Sides)) = 'LONG' ) SELECT AVG(FeelingLuckyTrades.priceDifference) - AVG(MomentumTrades.priceDifference) AS averageDifference FROM MomentumTrades, FeelingLuckyTrades",lite,bq090,trade_capture_report.lastpx; trade_capture_report.sides; trade_capture_report.strikeprice; trade_capture_report.targetcompid,4,14,True,ok,False,bq090 sf_bq091,PATENTS,snowflake,In which year did the assignee with the most applications in the patent category 'A61' file the most?,"WITH a61_applications AS ( SELECT DISTINCT p.""application_number"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p, LATERAL FLATTEN(input => p.""cpc"") c WHERE p.""filing_date"" IS NOT NULL AND p.""filing_date"" > 0 AND c.value:""code""::string LIKE 'A61%' AND p.""application_number"" IS NOT NULL UNION SELECT DISTINCT p.""application_number"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p, LATERAL FLATTEN(input => p.""ipc"") i WHERE p.""filing_date"" IS NOT NULL AND p.""filing_date"" > 0 AND i.value:""code""::string LIKE 'A61%' AND p.""application_number"" IS NOT NULL ), apps_with_meta AS ( SELECT p.""application_number"", CAST(FLOOR(p.""filing_date"" / 10000) AS INTEGER) AS ""filing_year"", p.""assignee_harmonized"", p.""assignee"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p JOIN a61_applications a ON a.""application_number"" = p.""application_number"" ), assignee_apps AS ( SELECT UPPER(TRIM(ah.value:""name""::string)) AS ""assignee_name"", awm.""application_number"", awm.""filing_year"" FROM apps_with_meta awm, LATERAL FLATTEN(input => awm.""assignee_harmonized"") ah WHERE ah.value:""name"" IS NOT NULL UNION ALL SELECT UPPER(TRIM(a.value::string)) AS ""assignee_name"", awm.""application_number"", awm.""filing_year"" FROM apps_with_meta awm, LATERAL FLATTEN(input => awm.""assignee"") a WHERE (awm.""assignee_harmonized"" IS NULL OR ARRAY_SIZE(awm.""assignee_harmonized"") = 0) AND a.value IS NOT NULL ), assignee_totals AS ( SELECT ""assignee_name"", COUNT(DISTINCT ""application_number"") AS ""total_apps"" FROM assignee_apps GROUP BY ""assignee_name"" ), top_assignee AS ( SELECT ""assignee_name"" FROM assignee_totals QUALIFY ROW_NUMBER() OVER (ORDER BY ""total_apps"" DESC, ""assignee_name"" ASC) = 1 ), year_counts AS ( SELECT aa.""filing_year"" AS ""year"", COUNT(DISTINCT aa.""application_number"") AS ""cnt"" FROM assignee_apps aa JOIN top_assignee ta ON aa.""assignee_name"" = ta.""assignee_name"" GROUP BY aa.""filing_year"" ) SELECT ""year"" FROM year_counts QUALIFY ROW_NUMBER() OVER (ORDER BY ""cnt"" DESC, ""year"" ASC) = 1;",snow,sf_bq091,publications.application_number; publications.assignee; publications.assignee_harmonized; publications.cpc; publications.filing_date; publications.ipc,6,79,True,ok,False,sf_bq091 sf_bq093,CRYPTO,snowflake,"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","WITH ""FILTERED_TX"" AS ( SELECT t.""hash"", t.""from_address"", COALESCE(t.""to_address"", t.""receipt_contract_address"") AS ""to_address"", COALESCE(t.""value"", 0) AS ""value"", COALESCE(t.""receipt_gas_used"", 0) AS ""receipt_gas_used"", COALESCE(t.""gas_price"", 0) AS ""gas_price"", COALESCE(t.""receipt_gas_used"", 0) * COALESCE(t.""gas_price"", 0) AS ""gas_fee"", b.""miner"" FROM CRYPTO.CRYPTO_ETHEREUM_CLASSIC.""TRANSACTIONS"" t JOIN CRYPTO.CRYPTO_ETHEREUM_CLASSIC.""BLOCKS"" b ON t.""block_number"" = b.""number"" WHERE t.""receipt_status"" = 1 AND TO_DATE(TO_TIMESTAMP_NTZ(t.""block_timestamp"" / 1000000)) = '2016-10-14' ), ""ADDRESS_CHANGES"" AS ( SELECT ""address"", SUM(""amount"") AS ""net_change"" FROM ( SELECT t.""from_address"" AS ""address"", -CAST(t.""value"" AS NUMBER(38, 9)) AS ""amount"" FROM ""FILTERED_TX"" t UNION ALL SELECT t.""to_address"" AS ""address"", CAST(t.""value"" AS NUMBER(38, 9)) AS ""amount"" FROM ""FILTERED_TX"" t WHERE t.""to_address"" IS NOT NULL UNION ALL SELECT t.""from_address"" AS ""address"", -CAST(t.""gas_fee"" AS NUMBER(38, 9)) AS ""amount"" FROM ""FILTERED_TX"" t UNION ALL SELECT t.""miner"" AS ""address"", CAST(t.""gas_fee"" AS NUMBER(38, 9)) AS ""amount"" FROM ""FILTERED_TX"" t ) AS contributions WHERE ""address"" IS NOT NULL GROUP BY ""address"" ), ""MAX_ADDR"" AS ( SELECT ""address"", ""net_change"" FROM ""ADDRESS_CHANGES"" QUALIFY ROW_NUMBER() OVER (ORDER BY ""net_change"" DESC, ""address"") = 1 ), ""MIN_ADDR"" AS ( SELECT ""address"", ""net_change"" FROM ""ADDRESS_CHANGES"" QUALIFY ROW_NUMBER() OVER (ORDER BY ""net_change"" ASC, ""address"") = 1 ) SELECT metrics.""metric"", metrics.""address"", metrics.""net_change"" FROM ( SELECT 'MAX' AS ""metric"", max_addr.""address"", COALESCE(max_addr.""net_change"", stats.""max_change"", 0) AS ""net_change"" FROM (SELECT MAX(""net_change"") AS ""max_change"" FROM ""ADDRESS_CHANGES"") stats LEFT JOIN ""MAX_ADDR"" max_addr ON 1 = 1 UNION ALL SELECT 'MIN' AS ""metric"", min_addr.""address"", COALESCE(min_addr.""net_change"", stats.""min_change"", 0) AS ""net_change"" FROM (SELECT MIN(""net_change"") AS ""min_change"" FROM ""ADDRESS_CHANGES"") stats LEFT JOIN ""MIN_ADDR"" min_addr ON 1 = 1 ) metrics ORDER BY metrics.""metric"" DESC;",snow,sf_bq093,blocks.miner; blocks.number; transactions.block_number; transactions.block_timestamp; transactions.from_address; transactions.gas_price; transactions.hash; transactions.receipt_contract_address; transactions.receipt_gas_used; transactions.receipt_status; transactions.to_address; transactions.value,12,286,True,fix,True,sf_bq093 sf_bq095,OPEN_TARGETS_PLATFORM_1,bigquery,"Generate a list of drugs from the table containing molecular details that have completed clinical trials for pancreatic endocrine carcinoma, disease ID EFO_0007416. Please include each drug's name, the target approved symbol, and links to the relevant clinical trials.","SELECT targets.approvedSymbol AS target_symbol, drugs.name AS drug_name, source_urls.element.url AS clinical_trial_reference_url, FROM `open-targets-prod.platform.evidence` AS evidence, UNNEST(evidence.urls.list) AS source_urls JOIN `open-targets-prod.platform.targets` AS targets ON evidence.targetId=targets.id JOIN `open-targets-prod.platform.molecule` AS drugs ON evidence.drugId=drugs.id WHERE datasourceId=""chembl"" AND diseaseId=""EFO_0007416"" AND evidence.clinicalStatus = ""Completed""",lite,bq095,evidence.clinicalstatus; evidence.datasourceid; evidence.diseaseid; evidence.drugid; evidence.targetid; evidence.urls; molecule.id; molecule.name; targets.approvedsymbol; targets.id,10,332,True,ok,False,bq095 sf_bq096,GBIF,bigquery,"Determine which year had the earliest date after January on which more than 10 sightings of Sterna paradisaea were recorded north of 40 degrees latitude. For each year, find the first day after January with over 10 sightings of this species in that region, and identify the year whose earliest such date is the earliest among all years.","WITH tenplus AS ( SELECT year, EXTRACT(DAYOFYEAR FROM DATE(eventdate)) AS dayofyear, COUNT(*) AS count FROM bigquery-public-data.gbif.occurrences WHERE eventdate IS NOT NULL AND species = 'Sterna paradisaea' AND decimallatitude > 40.0 AND month > 1 GROUP BY year, eventdate HAVING COUNT(*) > 10 ) SELECT year AS year FROM tenplus GROUP BY year ORDER BY MIN(dayofyear) LIMIT 1;",lite,bq096,occurrences.decimallatitude; occurrences.eventdate; occurrences.month; occurrences.species; occurrences.year,5,50,True,ok,False,bq096 sf_bq097,SDOH,bigquery,"What is the increasing amount of the average earnings per job between the years 2012 and 2017 for each geographic region in Massachusetts (indicated by ""MA"" at the end of GeoName)?","WITH bea_2012 AS ( SELECT GeoFIPS, GeoName, Earnings_per_job_avg AS earnings_2012 FROM `bigquery-public-data.sdoh_bea_cainc30.fips` WHERE Year='2012-01-01' AND ENDS_WITH(GeoName, ""MA"") IS TRUE ), bea_2017 AS ( SELECT GeoFIPS, GeoName, Earnings_per_job_avg AS earnings_2017 FROM `bigquery-public-data.sdoh_bea_cainc30.fips` WHERE Year='2017-01-01' AND ENDS_WITH(GeoName, ""MA"") IS TRUE ), earnings_diff AS ( SELECT bea_2017.GeoFIPS, bea_2017.GeoName, bea_2017.earnings_2017, bea_2012.earnings_2012, (bea_2017.earnings_2017 - bea_2012.earnings_2012) AS earnings_change FROM bea_2017 JOIN bea_2012 ON bea_2017.GeoFIPS = bea_2012.GeoFIPS ) SELECT * FROM earnings_diff WHERE earnings_change IS NOT NULL ORDER BY earnings_change DESC",lite,bq097,fips.earnings_per_job_avg; fips.geofips; fips.geoname; fips.year,4,4008,True,ok,False,bq097 sf_bq098,NEW_YORK_PLUS,bigquery,"For NYC yellow taxi trips where both the pickup and dropoff occurred between January 1 and 7, 2016, inclusive, calculate the percentage of trips with no tip in each pickup borough, ensuring that only trips where the dropoff occurs after the pickup are included, the passenger count is greater than zero, and the trip distance, tip amount, tolls amount, MTA tax, fare amount, and total amount are non-negative; define ""no tip"" trips as those where the tip rate is zero, with the tip rate calculated as (tip_amount × 100) divided by total_amount (and considered zero when total_amount is zero).","WITH t2 AS ( SELECT t.*, t.pickup_location_id as pickup_zone_id, tz.borough as pickup_borough FROM ( SELECT *, TIMESTAMP_DIFF(dropoff_datetime,pickup_datetime,SECOND) as time_duration_in_secs, (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 WHERE pickup_datetime BETWEEN '2016-01-01' AND '2016-01-07' AND dropoff_datetime BETWEEN '2016-01-01' AND '2016-01-07' AND TIMESTAMP_DIFF(dropoff_datetime,pickup_datetime,SECOND) > 0 AND passenger_count > 0 AND trip_distance >= 0 AND tip_amount >= 0 AND tolls_amount >= 0 AND mta_tax >= 0 AND fare_amount >= 0 AND total_amount >= 0 ), t3 AS (SELECT pickup_borough, (CASE WHEN tip_rate = 0 THEN 'no tip' WHEN tip_rate <= 5 THEN 'Less than 5%' WHEN tip_rate <= 10 THEN '5% to 10%' WHEN tip_rate <= 15 THEN '10% to 15%' WHEN tip_rate <= 20 THEN '15% to 20%' WHEN tip_rate <= 25 THEN '20% to 25%' ELSE 'More than 25%' END)as tip_category, COUNT(*) as no_of_trips FROM t2 GROUP BY 1,2 ORDER BY pickup_borough ASC), INFO AS ( SELECT pickup_borough , tip_category , Sum(no_of_trips) as no_of_trips, (CASE WHEN pickup_borough is null THEN (select sum(no_of_trips) FROM t3) WHEN pickup_borough is not null and tip_category is null THEN (select sum(no_of_trips) FROM t3) WHEN pickup_borough is not null and tip_category is not null THEN (select sum(no_of_trips) FROM t3 WHERE pickup_borough = m.pickup_borough) END) as parent_sum, ( Sum(no_of_trips) / ( CASE WHEN pickup_borough is null THEN (select sum(no_of_trips) FROM t3) WHEN pickup_borough is not null and tip_category is null THEN (select sum(no_of_trips) FROM t3) WHEN pickup_borough is not null and tip_category is not null THEN (select sum(no_of_trips) FROM t3 WHERE pickup_borough = m.pickup_borough) END ) ) as percentage FROM t3 m GROUP BY ROLLUP(pickup_borough, tip_category) order by 1, 2 ) SELECT pickup_borough, (SUM(CASE WHEN tip_category = 'no tip' THEN no_of_trips ELSE 0 END) * 100.0 / SUM(no_of_trips)) AS percentage_no_tip FROM t3 GROUP BY pickup_borough ORDER BY pickup_borough;",lite,bq098,taxi_zone_geom.borough; taxi_zone_geom.zone_id; tlc_yellow_trips_*.dropoff_datetime; tlc_yellow_trips_*.fare_amount; tlc_yellow_trips_*.mta_tax; tlc_yellow_trips_*.passenger_count; tlc_yellow_trips_*.pickup_datetime; tlc_yellow_trips_*.pickup_location_id; tlc_yellow_trips_*.tip_amount; tlc_yellow_trips_*.tolls_amount; tlc_yellow_trips_*.total_amount; tlc_yellow_trips_*.trip_distance,12,435,True,ok,False,bq098 sf_bq099,PATENTS,snowflake,"For patent class A01B3, I want to analyze the information of the top 3 assignees based on the total number of applications. Please provide the following five pieces of information: the name of this assignee, total number of applications, the year with the most applications, the number of applications in that year, and the country code with the most applications during that year.","WITH ""base"" AS ( SELECT DISTINCT UPPER(""fa"".""VALUE"":""name""::string) AS ""assignee_name"", ""p"".""application_number"" AS ""application_number"", CASE WHEN ""p"".""filing_date"" IS NOT NULL AND ""p"".""filing_date"" > 0 THEN FLOOR(""p"".""filing_date""/10000) END AS ""filing_year"", ""p"".""country_code"" AS ""country_code"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" AS ""p"", LATERAL FLATTEN(input => ""p"".""cpc"") AS ""fc"", LATERAL FLATTEN(input => ""p"".""assignee_harmonized"") AS ""fa"" WHERE UPPER(""fc"".""VALUE"":""code""::string) LIKE 'A01B3%' ), ""assignee_totals"" AS ( SELECT ""assignee_name"", COUNT(DISTINCT ""application_number"") AS ""total_applications"" FROM ""base"" GROUP BY ""assignee_name"" ), ""per_year"" AS ( SELECT ""assignee_name"", ""filing_year"", COUNT(DISTINCT ""application_number"") AS ""apps_in_year"" FROM ""base"" WHERE ""filing_year"" IS NOT NULL GROUP BY ""assignee_name"", ""filing_year"" ), ""top_year"" AS ( SELECT ""assignee_name"", ""filing_year"" AS ""top_year"", ""apps_in_year"" FROM ( SELECT ""assignee_name"", ""filing_year"", ""apps_in_year"", ROW_NUMBER() OVER (PARTITION BY ""assignee_name"" ORDER BY ""apps_in_year"" DESC, ""filing_year"" ASC) AS ""rn"" FROM ""per_year"" ) WHERE ""rn"" = 1 ), ""per_country_year"" AS ( SELECT ""assignee_name"", ""filing_year"", ""country_code"", COUNT(DISTINCT ""application_number"") AS ""apps_in_year_country"" FROM ""base"" WHERE ""filing_year"" IS NOT NULL GROUP BY ""assignee_name"", ""filing_year"", ""country_code"" ), ""top_country"" AS ( SELECT ""pc"".""assignee_name"", ""pc"".""filing_year"", ""pc"".""country_code"" AS ""top_country_code"", ""pc"".""apps_in_year_country"" FROM ( SELECT ""assignee_name"", ""filing_year"", ""country_code"", ""apps_in_year_country"", ROW_NUMBER() OVER (PARTITION BY ""assignee_name"", ""filing_year"" ORDER BY ""apps_in_year_country"" DESC, ""country_code"" ASC) AS ""rn"" FROM ""per_country_year"" ) AS ""pc"" WHERE ""pc"".""rn"" = 1 ), ""ranked_assignees"" AS ( SELECT ""assignee_name"", ""total_applications"", ROW_NUMBER() OVER (ORDER BY ""total_applications"" DESC, ""assignee_name"" ASC) AS ""assignee_rank"" FROM ""assignee_totals"" ) SELECT ""r"".""assignee_name"", ""r"".""total_applications"", ""y"".""top_year"", ""y"".""apps_in_year"" AS ""applications_in_top_year"", ""c"".""top_country_code"" FROM ""ranked_assignees"" AS ""r"" JOIN ""top_year"" AS ""y"" ON ""r"".""assignee_name"" = ""y"".""assignee_name"" LEFT JOIN ""top_country"" AS ""c"" ON ""c"".""assignee_name"" = ""y"".""assignee_name"" AND ""c"".""filing_year"" = ""y"".""top_year"" WHERE ""r"".""assignee_rank"" <= 3 ORDER BY ""r"".""total_applications"" DESC, ""r"".""assignee_name"" ASC;",snow,sf_bq099,publications.application_number; publications.assignee_harmonized; publications.country_code; publications.cpc; publications.filing_date,5,79,True,ok,False,sf_bq099 sf_bq102,GNOMAD,bigquery,"Identify which start positions are associated with missense variants in the BRCA1 gene on chromosome 17, where the reference base is 'C' and the alternate base is 'T'. Using data from the gnomAD v2.1.1 version.","WITH gene_region AS ( SELECT MIN(start_position) AS start_pos, MAX(end_position) AS end_pos FROM `bigquery-public-data.gnomAD.v2_1_1_genomes__chr17` AS main_table WHERE EXISTS ( SELECT 1 FROM UNNEST(main_table.alternate_bases) AS alternate_bases WHERE EXISTS ( SELECT 1 FROM UNNEST(alternate_bases.vep) AS vep WHERE vep.SYMBOL = 'BRCA1' ) ) ) SELECT DISTINCT start_position FROM `bigquery-public-data.gnomAD.v2_1_1_genomes__chr17` AS main_table, UNNEST(main_table.alternate_bases) AS alternate_bases, UNNEST(alternate_bases.vep) AS vep, gene_region WHERE main_table.start_position >= gene_region.start_pos AND main_table.start_position <= gene_region.end_pos AND REGEXP_CONTAINS(vep.Consequence, r""missense_variant"") AND reference_bases = ""C"" AND alternate_bases.alt = ""T"" ",lite,bq102,v2_1_1_genomes__chr_*.alternate_bases; v2_1_1_genomes__chr_*.end_position; v2_1_1_genomes__chr_*.reference_bases; v2_1_1_genomes__chr_*.start_position,4,1150,True,ok,False,bq102 sf_bq103,GNOMAD,bigquery,"Generate summary statistics on genetic variants in the region between positions 55039447 and 55064852 on chromosome 1. This includes the number of variants, the total allele count, the total number of alleles, and distinct gene symbols (using Variant Effect Predictor, VEP, for gene annotation). Additionally, compute the density of mutations by dividing the length of the region by the number of variants. Using data from the gnomAD v3 version.","WITH summary_stats AS ( SELECT COUNT(1) AS num_variants, SUM((SELECT alt.AC FROM UNNEST(alternate_bases) AS alt)) AS sum_AC, SUM(AN) AS sum_AN, -- Also include some information from Variant Effect Predictor (VEP). STRING_AGG(DISTINCT (SELECT annot.symbol FROM UNNEST(alternate_bases) AS alt, UNNEST(vep) AS annot LIMIT 1), ', ') AS genes FROM bigquery-public-data.gnomAD.v3_genomes__chr1 AS main_table WHERE start_position >= 55039447 AND start_position <= 55064852 ) SELECT ROUND((55064852 - 55039447) / num_variants, 3) AS burden_of_mutation, * FROM summary_stats;",lite,bq103,v3_genomes__chr_*.alternate_bases; v3_genomes__chr_*.an; v3_genomes__chr_*.start_position,3,1150,True,ok,False,bq103 sf_bq104,GOOGLE_TRENDS,snowflake,"Based on the most recent refresh date, identify the top-ranked rising search term for the week that is exactly one year prior to the latest available week in the dataset.","WITH base AS ( SELECT tr.""term"", tr.""week"", tr.""score"", tr.""rank"", tr.""percent_gain"", tr.""refresh_date"" FROM GOOGLE_TRENDS.GOOGLE_TRENDS.TOP_RISING_TERMS tr WHERE tr.""week"" IS NOT NULL UNION ALL SELECT ir.""term"", ir.""week"", ir.""score"", ir.""rank"", ir.""percent_gain"", ir.""refresh_date"" FROM GOOGLE_TRENDS.GOOGLE_TRENDS.INTERNATIONAL_TOP_RISING_TERMS ir WHERE ir.""week"" IS NOT NULL ), latest_refresh AS ( SELECT MAX(""refresh_date"") AS ""refresh_date"" FROM base ), latest_week_in_latest AS ( SELECT MAX(b.""week"") AS ""week"" FROM base b JOIN latest_refresh lr ON b.""refresh_date"" = lr.""refresh_date"" ), target AS ( -- Use 52 weeks prior to align with weekly cadence for ""exactly one year"" SELECT DATEADD('week', -52, lw.""week"") AS ""target_week"" FROM latest_week_in_latest lw ), cand_exact_latest AS ( -- priority 1: exact target week within latest refresh SELECT 1 AS prio, b.""refresh_date"", b.""week"" FROM base b JOIN latest_refresh lr ON b.""refresh_date"" = lr.""refresh_date"" JOIN target t ON b.""week"" = t.""target_week"" GROUP BY b.""refresh_date"", b.""week"" ), cand_exact_any AS ( -- priority 2: exact target week across any refresh (choose latest refresh that has it) SELECT 2 AS prio, x.""refresh_date"", x.""week"" FROM ( SELECT b.""refresh_date"", b.""week"", ROW_NUMBER() OVER (PARTITION BY b.""week"" ORDER BY b.""refresh_date"" DESC) AS rn FROM base b JOIN target t ON b.""week"" = t.""target_week"" ) x WHERE x.rn = 1 ), candidates AS ( SELECT * FROM cand_exact_latest UNION ALL SELECT * FROM cand_exact_any ), selected_context AS ( SELECT ""refresh_date"", ""week"" FROM ( SELECT ""refresh_date"", ""week"", ROW_NUMBER() OVER (ORDER BY prio) AS rn FROM candidates ) WHERE rn = 1 ), rows_in_context AS ( SELECT b.* FROM base b JOIN selected_context sc ON b.""refresh_date"" = sc.""refresh_date"" AND b.""week"" = sc.""week"" ), terms_aggregated AS ( SELECT ""term"", MIN(""rank"") AS best_rank, MAX(""percent_gain"") AS best_percent_gain, MAX(""score"") AS best_score FROM rows_in_context GROUP BY ""term"" ) SELECT ta.""term"" FROM terms_aggregated ta QUALIFY ROW_NUMBER() OVER ( ORDER BY ta.best_rank ASC NULLS LAST, ta.best_percent_gain DESC NULLS LAST, ta.best_score DESC NULLS LAST, ta.""term"" ) = 1;",snow,sf_bq104,international_top_rising_terms.percent_gain; international_top_rising_terms.rank; international_top_rising_terms.refresh_date; international_top_rising_terms.score; international_top_rising_terms.term; international_top_rising_terms.week; top_rising_terms.percent_gain; top_rising_terms.rank; top_rising_terms.refresh_date; top_rising_terms.score; top_rising_terms.term; top_rising_terms.week,12,34,True,ok,False,sf_bq104 sf_bq105,NHTSA_TRAFFIC_FATALITIES_PLUS,bigquery,"According to the 2015 and 2016 accident and driver distraction, and excluding cases where the driver’s distraction status is recorded as 'Not Distracted,' 'Unknown if Distracted,' or 'Not Reported,' how many traffic accidents per 100,000 people were caused by driver distraction in each U.S. state for those two years, based on 2010 census population data, and which five states each year had the highest rates?","SELECT * FROM ( SELECT '2015' AS year, COUNT(a.consecutive_number) AS total, a.state_name AS state, c.state_pop AS population, (COUNT(a.consecutive_number) / c.state_pop * 100000) AS rate_per_100000 FROM `bigquery-public-data.nhtsa_traffic_fatalities.accident_2015` a JOIN `bigquery-public-data.nhtsa_traffic_fatalities.distract_2015` b ON a.consecutive_number = b.consecutive_number JOIN ( SELECT SUM(d.population) AS state_pop, e.state_name AS state FROM `bigquery-public-data.census_bureau_usa.population_by_zip_2010` d JOIN `bigquery-public-data.utility_us.zipcode_area` e ON d.zipcode = e.zipcode GROUP BY state ) c ON c.state = a.state_name WHERE b.driver_distracted_by_name NOT IN ('Not Distracted', 'Unknown if Distracted', 'Not Reported') GROUP BY state, population, c.state_pop ORDER BY rate_per_100000 DESC LIMIT 5 ) UNION ALL ( SELECT '2016' AS year, COUNT(a.consecutive_number) AS total, a.state_name AS state, c.state_pop AS population, (COUNT(a.consecutive_number) / c.state_pop * 100000) AS rate_per_100000 FROM `bigquery-public-data.nhtsa_traffic_fatalities.accident_2016` a JOIN `bigquery-public-data.nhtsa_traffic_fatalities.distract_2016` b ON a.consecutive_number = b.consecutive_number JOIN ( SELECT SUM(d.population) AS state_pop, e.state_name AS state FROM `bigquery-public-data.census_bureau_usa.population_by_zip_2010` d JOIN `bigquery-public-data.utility_us.zipcode_area` e ON d.zipcode = e.zipcode GROUP BY state ) c ON c.state = a.state_name WHERE b.driver_distracted_by_name NOT IN ('Not Distracted', 'Unknown if Distracted', 'Not Reported') GROUP BY state, population, c.state_pop ORDER BY rate_per_100000 DESC LIMIT 5 )",lite,bq105,accident_*.consecutive_number; accident_*.state_name; distract_*.consecutive_number; distract_*.driver_distracted_by_name; population_by_zip_*.population; population_by_zip_*.zipcode; zipcode_area.state_name; zipcode_area.zipcode,8,812,True,ok,False,bq105 sf_bq109,OPEN_TARGETS_GENETICS_1,bigquery,"Find the average, variance, max-min difference, and the QTL source(right study) of the maximum log2(h4/h3) for data where right gene id is ""ENSG00000169174"", h4 > 0.8, h3 < 0.02, reported trait includes ""lesterol levels"", right biological feature is ""IPSC"", and the variant is '1_55029009_C_T'.","WITH coloc_stats AS ( SELECT coloc.coloc_log2_h4_h3, coloc.right_study AS qtl_source FROM `open-targets-genetics.genetics.variant_disease_coloc` AS coloc JOIN `open-targets-genetics.genetics.studies` AS studies ON coloc.left_study = studies.study_id WHERE coloc.right_gene_id = ""ENSG00000169174"" AND coloc.coloc_h4 > 0.8 AND coloc.coloc_h3 < 0.02 AND studies.trait_reported LIKE ""%lesterol levels%"" AND coloc.right_bio_feature = 'IPSC' AND CONCAT(coloc.left_chrom, '_', coloc.left_pos, '_', coloc.left_ref, '_', coloc.left_alt) = '1_55029009_C_T' ), max_value AS ( SELECT MAX(coloc_log2_h4_h3) AS max_log2_h4_h3 FROM coloc_stats ) SELECT AVG(coloc_log2_h4_h3) AS average, VAR_SAMP(coloc_log2_h4_h3) AS variance, MAX(coloc_log2_h4_h3) - MIN(coloc_log2_h4_h3) AS max_min_difference, (SELECT qtl_source FROM coloc_stats WHERE coloc_log2_h4_h3 = (SELECT max_log2_h4_h3 FROM max_value)) AS qtl_source_of_max FROM coloc_stats;",lite,bq109,studies.study_id; studies.trait_reported; variant_disease_coloc.coloc_h3; variant_disease_coloc.coloc_h4; variant_disease_coloc.coloc_log2_h4_h3; variant_disease_coloc.left_alt; variant_disease_coloc.left_chrom; variant_disease_coloc.left_pos; variant_disease_coloc.left_ref; variant_disease_coloc.left_study; variant_disease_coloc.right_bio_feature; variant_disease_coloc.right_gene_id; variant_disease_coloc.right_study,13,293,True,ok,False,bq109 sf_bq110,SDOH,bigquery,What is the change in the number of homeless veterans between 2012 and 2018 for each CoC region in New York that has data available in both years?,"WITH homeless_2012 AS ( SELECT Homeless_Veterans AS Vet12, CoC_Name FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc` WHERE SUBSTR(CoC_Number,0,2) = ""NY"" AND Count_Year = 2012 ), homeless_2018 AS ( SELECT Homeless_Veterans AS Vet18, CoC_Name FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc` WHERE SUBSTR(CoC_Number,0,2) = ""NY"" AND Count_Year = 2018 ), veterans_change AS ( SELECT homeless_2012.COC_Name, Vet12, Vet18, Vet18 - Vet12 AS VetChange FROM homeless_2018 JOIN homeless_2012 ON homeless_2018.CoC_Name = homeless_2012.CoC_Name ) SELECT COC_Name, VetChange FROM veterans_change ORDER BY CoC_Name;",lite,bq110,hud_pit_by_coc.coc_name; hud_pit_by_coc.coc_number; hud_pit_by_coc.count_year; hud_pit_by_coc.homeless_veterans,4,4008,True,ok,False,bq110 sf_bq112,BLS,bigquery,"Between 1998 and 2017, for Allegheny County in the Pittsburgh area, did the average annual wages for all industries keep pace with the inflation of all consumer items, and what were the respective percentage growth rates (to two decimal places) for wages and the CPI over that period?","WITH geo AS ( SELECT DISTINCT geo_id FROM `bigquery-public-data.geo_us_boundaries.counties` WHERE county_name = ""Allegheny"" ), avg_wage_1998 AS( SELECT ROUND(AVG(avg_wkly_wage_10_total_all_industries) * 52, 2) AS wages_1998 FROM `bigquery-public-data.bls_qcew.1998*` WHERE geoid = (SELECT geo_id FROM geo) --Selecting Allgeheny County ), avg_wage_2017 AS ( SELECT ROUND(AVG(avg_wkly_wage_10_total_all_industries) * 52, 2) AS wages_2017 FROM `bigquery-public-data.bls_qcew.2017*` WHERE geoid = (SELECT geo_id FROM geo) --Selecting Allgeheny County ), avg_cpi_1998 AS ( SELECT AVG(value) AS cpi_1998 FROM `bigquery-public-data.bls.cpi_u` c WHERE year = 1998 AND item_code in ( SELECT DISTINCT item_code FROM `bigquery-public-data.bls.cpi_u` WHERE LOWER(item_name) = ""all items"" ) AND area_code = ( SELECT DISTINCT area_code FROM `bigquery-public-data.bls.cpi_u` WHERE area_name LIKE '%Pittsburgh%' ) ), -- A104 is the code for Pittsburgh, PA -- SA0 is the code for all items avg_cpi_2017 AS( SELECT AVG(value) AS cpi_2017 FROM `bigquery-public-data.bls.cpi_u` c WHERE year = 2017 AND item_code in ( SELECT DISTINCT item_code FROM `bigquery-public-data.bls.cpi_u` WHERE LOWER(item_name) = ""all items"" ) AND area_code = ( SELECT DISTINCT area_code FROM `bigquery-public-data.bls.cpi_u` WHERE area_name LIKE '%Pittsburgh%' ) ) -- A104 is the code for Pittsburgh, PA -- SA0 is the code for all items SELECT ROUND((wages_2017 - wages_1998) / wages_1998 * 100, 2) AS wages_percent_change, ROUND((cpi_2017 - cpi_1998) / cpi_1998 * 100, 2) AS cpi_percent_change FROM avg_wage_2017, avg_wage_1998, avg_cpi_2017, avg_cpi_1998",lite,bq112,_1990_q1.avg_wkly_wage_10_total_all_industries; _1990_q1.geoid; counties.county_name; counties.geo_id; cpi_u.area_code; cpi_u.area_name; cpi_u.item_code; cpi_u.item_name; cpi_u.value; cpi_u.year,10,481,True,ok,False,bq112 sf_bq113,BLS,bigquery,"Which county in Utah experienced the greatest percentage increase in construction employment from 2000 to 2018, calculated by averaging the employment levels during the third month of each quarter in those years? What is the corresponding percentage increase?","WITH utah_code AS ( SELECT DISTINCT geo_id FROM bigquery-public-data.geo_us_boundaries.states WHERE state_name = 'Utah' ), e2000 as( SELECT AVG(month3_emplvl_23_construction) AS construction_employees_2000, geoid FROM `bigquery-public-data.bls_qcew.2000_*` WHERE geoid LIKE CONCAT((SELECT geo_id FROM utah_code), '%') GROUP BY geoid), e2018 AS ( SELECT AVG(month3_emplvl_23_construction) AS construction_employees_2018, geoid, FROM `bigquery-public-data.bls_qcew.2018_*` e2018 WHERE geoid LIKE CONCAT((SELECT geo_id FROM utah_code), '%') GROUP BY geoid) SELECT c.county_name AS county, (construction_employees_2018 - construction_employees_2000) / construction_employees_2000 * 100 AS increase_rate FROM e2000 JOIN e2018 USING (geoid) JOIN `bigquery-public-data.geo_us_boundaries.counties` c ON c.geo_id = e2018.geoid WHERE c.state_fips_code = (SELECT geo_id FROM utah_code) ORDER BY increase_rate desc LIMIT 1",lite,bq113,_1990_q1.geoid; _1990_q1.month3_emplvl_23_construction; counties.county_name; counties.geo_id; counties.state_fips_code; states.geo_id; states.state_name,7,481,True,ok,False,bq113 sf_bq114,OPENAQ,bigquery,"Which three cities have the largest difference between their 1990 EPA PM2.5 measurements (using units_of_measure = 'Micrograms/cubic meter (LC)' and parameter_name = 'Acceptable PM2.5 AQI & Speciation Mass') and their 2020 OpenAQ PM2.5 measurements (where pollutant = 'pm25' based on the year extracted from the timestamp), with both datasets matched by latitude and longitude rounded to two decimals, and the difference ordered from greatest to least?","SELECT aq.city, epa.arithmetic_mean, aq.value, aq.timestamp, (epa.arithmetic_mean - aq.value) FROM `bigquery-public-data.openaq.global_air_quality` AS aq JOIN `bigquery-public-data.epa_historical_air_quality.air_quality_annual_summary` AS epa ON ROUND(aq.latitude, 2) = ROUND(epa.latitude, 2) AND ROUND(aq.longitude, 2) = ROUND(epa.longitude, 2) WHERE epa.units_of_measure = ""Micrograms/cubic meter (LC)"" AND epa.parameter_name = ""Acceptable PM2.5 AQI & Speciation Mass"" AND epa.year = 1990 AND aq.pollutant = ""pm25"" AND EXTRACT(YEAR FROM aq.timestamp) = 2020 ORDER BY (epa.arithmetic_mean - aq.value) DESC LIMIT 3 ",lite,bq114,air_quality_annual_summary.arithmetic_mean; air_quality_annual_summary.latitude; air_quality_annual_summary.longitude; air_quality_annual_summary.parameter_name; air_quality_annual_summary.units_of_measure; air_quality_annual_summary.year; global_air_quality.city; global_air_quality.latitude; global_air_quality.longitude; global_air_quality.pollutant; global_air_quality.timestamp; global_air_quality.value,12,891,True,ok,False,bq114 sf_bq115,CENSUS_BUREAU_INTERNATIONAL,bigquery,Which country has the highest percentage of population under the age of 25 in 2017?,"SELECT country_name FROM (SELECT age.country_name, SUM(age.population) AS under_25, pop.midyear_population AS total, ROUND((SUM(age.population) / pop.midyear_population) * 100,2) AS pct_under_25 FROM ( SELECT country_name, population, country_code FROM `bigquery-public-data.census_bureau_international.midyear_population_agespecific` WHERE year =2017 AND age < 25) age INNER JOIN ( SELECT midyear_population, country_code FROM `bigquery-public-data.census_bureau_international.midyear_population` WHERE year = 2017) pop ON age.country_code = pop.country_code GROUP BY 1, 3 ORDER BY 4 DESC ) LIMIT 1",lite,bq115,midyear_population.country_code; midyear_population.midyear_population; midyear_population.year; midyear_population_agespecific.age; midyear_population_agespecific.country_code; midyear_population_agespecific.country_name; midyear_population_agespecific.population; midyear_population_agespecific.year,8,165,True,fix,True,bq115 sf_bq119,NOAA_DATA,bigquery,"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.","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;",lite,bq119,hurricanes.basin; hurricanes.iso_time; hurricanes.latitude; hurricanes.longitude; hurricanes.name; hurricanes.season; hurricanes.sid; hurricanes.usa_wind,8,745,True,ok,False,bq119 sf_bq120,SDOH,bigquery,"Identify the top 10 regions (counties) with the highest total number of SNAP-participating households, using the 2017 5-year ACS county-level data and SNAP enrollment data from January 1, 2017, excluding regions where the total SNAP participation is zero. For each of these regions, calculate the ratio of households earning under $20,000 to the total number of SNAP-participating households.","WITH acs_2017 AS ( SELECT geo_id, income_less_10000 AS i10, income_10000_14999 AS i15, income_15000_19999 AS i20 FROM `bigquery-public-data.census_bureau_acs.county_2017_5yr` ), snap_2017_Jan AS ( SELECT FIPS, SNAP_All_Participation_Households AS snap_total FROM `bigquery-public-data.sdoh_snap_enrollment.snap_enrollment` WHERE Date = '2017-01-01' ) SELECT acs_2017.geo_id, snap_2017_Jan.snap_total, (acs_2017.i10 + acs_2017.i15 + acs_2017.i20) As households_under_20, (acs_2017.i10 + acs_2017.i15 + acs_2017.i20)/snap_2017_Jan.snap_total As under_20_snap_ratio FROM acs_2017 JOIN snap_2017_Jan ON acs_2017.geo_id = snap_2017_Jan.FIPS WHERE snap_2017_Jan.snap_total > 0 ORDER BY snap_2017_Jan.snap_total DESC LIMIT 10 ",lite,bq120,county_*.geo_id; county_*.income_10000_14999; county_*.income_15000_19999; county_*.income_less_10000; snap_enrollment.date; snap_enrollment.fips; snap_enrollment.snap_all_participation_households,7,4008,True,ok,False,bq120 sf_bq121,STACKOVERFLOW,snowflake,"How do the average reputation and number of badges vary among Stack Overflow users based on the number of complete years they have been members, considering only those who joined on or before October 1, 2021?","WITH ref AS ( SELECT DATE '2021-10-01' AS ""ref_date"" ), users_base AS ( SELECT ""id"" AS ""user_id"", CAST(TO_TIMESTAMP(""creation_date"" / 1000000.0) AS DATE) AS ""creation_date_dt"", ""reputation"" FROM ""STACKOVERFLOW"".""STACKOVERFLOW"".""USERS"" ), users_filtered AS ( SELECT ub.* FROM users_base ub JOIN ref r ON 1=1 WHERE ub.""creation_date_dt"" <= r.""ref_date"" ), users_years AS ( SELECT ""user_id"", ""creation_date_dt"", ""reputation"", (DATEDIFF(year, ""creation_date_dt"", r.""ref_date"") - CASE WHEN DATEADD(year, DATEDIFF(year, ""creation_date_dt"", r.""ref_date""), ""creation_date_dt"") > r.""ref_date"" THEN 1 ELSE 0 END ) AS ""complete_years"" FROM users_filtered uf JOIN ref r ON 1=1 ), badges_per_user AS ( SELECT ""user_id"", COUNT(*) AS ""num_badges"" FROM ""STACKOVERFLOW"".""STACKOVERFLOW"".""BADGES"" GROUP BY ""user_id"" ) SELECT uy.""complete_years"" AS ""complete_years"", COALESCE(CAST(AVG(uy.""reputation"") AS FLOAT), 0) AS ""avg_reputation"", COALESCE(CAST(AVG(COALESCE(b.""num_badges"", 0)) AS FLOAT), 0) AS ""avg_badges"", COUNT(*) AS ""user_count"" FROM users_years uy LEFT JOIN badges_per_user b ON uy.""user_id"" = b.""user_id"" GROUP BY uy.""complete_years"" ORDER BY uy.""complete_years"" ASC;",snow,sf_bq121,badges.user_id; users.creation_date; users.id; users.reputation,4,376,True,fix,True,sf_bq121 sf_bq123,STACKOVERFLOW,bigquery,"You need to determine which day of the week has the third highest percentage of questions on Stack Overflow that receive an answer within an hour. To do this, use the question creation date from the posts_questions table and the earliest answer creation date from the posts_answers table. Once you’ve calculated the percentage of questions that get answered within an hour for each day, identify the day with the third highest percentage and report that percentage.","WITH first_answers AS ( SELECT parent_id AS question_id, MIN(creation_date) AS first_answer_date FROM `bigquery-public-data.stackoverflow.posts_answers` GROUP BY parent_id ) SELECT FORMAT_DATE('%A', DATE(q.creation_date)) AS question_day, SUM(CASE WHEN f.first_answer_date IS NOT NULL AND TIMESTAMP_DIFF(f.first_answer_date, q.creation_date, MINUTE) <= 60 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS percent_questions FROM `bigquery-public-data.stackoverflow.posts_questions` q LEFT JOIN first_answers f ON q.id = f.question_id GROUP BY question_day ORDER BY percent_questions DESC LIMIT 1 OFFSET 2",lite,bq123,posts_*.creation_date; posts_*.id; posts_*.parent_id,3,376,True,fix,True,bq123 sf_bq124,FHIR_SYNTHEA,bigquery,"Among all patients, how many individuals remain alive (i.e., with no recorded deceased.dateTime), have a diagnosis of either Diabetes or Hypertension, and are prescribed at least seven distinct active medications?","With INFO AS ( SELECT MR.patientId, P.last_name, ARRAY_TO_STRING(P.first_name, "" "") AS First_name, Condition.Codes, Condition.Conditions, MR.med_count AS COUNT_NUMBER FROM (SELECT id, name[safe_offset(0)].family as last_name, name[safe_offset(0)].given as first_name, TIMESTAMP(deceased.dateTime) AS deceased_datetime FROM `bigquery-public-data.fhir_synthea.patient`) AS P JOIN (SELECT subject.patientId as patientId, COUNT(DISTINCT medication.codeableConcept.coding[safe_offset(0)].code) AS med_count FROM `bigquery-public-data.fhir_synthea.medication_request` WHERE status = 'active' GROUP BY 1 ) AS MR ON MR.patientId = P.id JOIN (SELECT PatientId, STRING_AGG(DISTINCT condition_desc, "", "") AS Conditions, STRING_AGG(DISTINCT condition_code, "", "") AS Codes FROM( SELECT subject.patientId as PatientId, code.coding[safe_offset(0)].code condition_code, code.coding[safe_offset(0)].display condition_desc FROM `bigquery-public-data.fhir_synthea.condition` wHERE code.coding[safe_offset(0)].display = 'Diabetes' OR code.coding[safe_offset(0)].display = 'Hypertension' ) GROUP BY PatientId ) AS Condition ON MR.patientId = Condition.PatientId WHERE med_count >= 7 AND P.deceased_datetime is NULL /*only alive patients*/ GROUP BY patientId, last_name, first_name, Condition.Codes, Condition.Conditions, MR.med_count ORDER BY last_name ) SELECT COUNT(*) FROM INFO",lite,bq124,condition.code; condition.subject; medication_request.status; medication_request.subject; patient.deceased; patient.id; patient.name,7,456,True,fix,True,bq124 sf_bq126,THE_MET,bigquery,"What are the titles, artist names, mediums, and original image URLs of objects with 'Photograph' in their names from the 'Photographs' department, created not by an unknown artist, with an object end date of 1839 or earlier?","SELECT o.artist_display_name, o.title, o.object_end_date, o.medium, i.original_image_url FROM ( SELECT object_id, title, artist_display_name, object_end_date, medium FROM `bigquery-public-data.the_met.objects` WHERE department = ""Photographs"" AND object_name LIKE ""%Photograph%"" AND artist_display_name != ""Unknown"" AND object_end_date <= 1839 ) o INNER JOIN ( SELECT original_image_url, object_id FROM `bigquery-public-data.the_met.images` ) i ON o.object_id = i.object_id ORDER BY o.object_end_date ;",lite,bq126,images.object_id; images.original_image_url; objects.artist_display_name; objects.department; objects.medium; objects.object_end_date; objects.object_id; objects.object_name; objects.title,9,61,True,fix,True,bq126 sf_bq127,PATENTS_GOOGLE,snowflake,"For each publication family whose earliest publication was first published in January 2015, please provide the earliest publication date, the distinct publication numbers, their country codes, the distinct CPC and IPC codes, distinct families (namely, the ids) that cite and are cited by this publication family. Please present all lists as comma-separated values, sorted alphabetically","WITH ""FAMS"" AS ( SELECT ""family_id"", MIN(""publication_date"") AS ""earliest_publication_date_num"" FROM ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""PUBLICATIONS"" WHERE ""family_id"" IS NOT NULL GROUP BY ""family_id"" HAVING MIN(""publication_date"") BETWEEN 20150101 AND 20150131 ), ""FAMILY_PUBS"" AS ( SELECT ""F"".""family_id"", ""F"".""earliest_publication_date_num"", TRIM(""P"".""publication_number"") AS ""publication_number"", TRIM(""P"".""country_code"") AS ""country_code"", ""P"".""cpc"" AS ""cpc"", ""P"".""ipc"" AS ""ipc"", ""P"".""citation"" AS ""citation"" FROM ""FAMS"" AS ""F"" JOIN ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""PUBLICATIONS"" AS ""P"" ON ""P"".""family_id"" = ""F"".""family_id"" ), ""PUBS_AGG"" AS ( SELECT ""family_id"", LISTAGG(DISTINCT ""publication_number"", ', ') WITHIN GROUP (ORDER BY ""publication_number"") AS ""publication_numbers"" FROM ""FAMILY_PUBS"" GROUP BY ""family_id"" ), ""COUNTRIES_AGG"" AS ( SELECT ""family_id"", LISTAGG(DISTINCT ""country_code"", ', ') WITHIN GROUP (ORDER BY ""country_code"") AS ""country_codes"" FROM ""FAMILY_PUBS"" WHERE ""country_code"" IS NOT NULL AND ""country_code"" != '' GROUP BY ""family_id"" ), ""CPC_AGG"" AS ( SELECT ""FP"".""family_id"", LISTAGG(DISTINCT TRIM(""CPC_ITEM"".""VALUE"":""code""::STRING), ', ') WITHIN GROUP (ORDER BY TRIM(""CPC_ITEM"".""VALUE"":""code""::STRING)) AS ""cpc_codes"" FROM ""FAMILY_PUBS"" AS ""FP"", LATERAL FLATTEN(INPUT => ""FP"".""cpc"") AS ""CPC_ITEM"" WHERE ""CPC_ITEM"".""VALUE"":""code"" IS NOT NULL AND TRIM(""CPC_ITEM"".""VALUE"":""code""::STRING) != '' GROUP BY ""FP"".""family_id"" ), ""IPC_AGG"" AS ( SELECT ""FP"".""family_id"", LISTAGG(DISTINCT TRIM(""IPC_ITEM"".""VALUE"":""code""::STRING), ', ') WITHIN GROUP (ORDER BY TRIM(""IPC_ITEM"".""VALUE"":""code""::STRING)) AS ""ipc_codes"" FROM ""FAMILY_PUBS"" AS ""FP"", LATERAL FLATTEN(INPUT => ""FP"".""ipc"") AS ""IPC_ITEM"" WHERE ""IPC_ITEM"".""VALUE"":""code"" IS NOT NULL AND TRIM(""IPC_ITEM"".""VALUE"":""code""::STRING) != '' GROUP BY ""FP"".""family_id"" ), ""CITED_PUBS"" AS ( SELECT ""FP"".""family_id"" AS ""source_family_id"", TRIM(""CIT"".""VALUE"":""publication_number""::STRING) AS ""cited_pubnum"" FROM ""FAMILY_PUBS"" AS ""FP"", LATERAL FLATTEN(INPUT => ""FP"".""citation"") AS ""CIT"" WHERE TRIM(""CIT"".""VALUE"":""publication_number""::STRING) IS NOT NULL AND TRIM(""CIT"".""VALUE"":""publication_number""::STRING) != '' ), ""CITED_FAMILIES"" AS ( SELECT DISTINCT ""CP"".""source_family_id"", ""P_CITED"".""family_id"" AS ""cited_family_id"" FROM ""CITED_PUBS"" AS ""CP"" JOIN ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""PUBLICATIONS"" AS ""P_CITED"" ON TRIM(""P_CITED"".""publication_number"") = ""CP"".""cited_pubnum"" WHERE ""P_CITED"".""family_id"" IS NOT NULL AND ""P_CITED"".""family_id"" != ""CP"".""source_family_id"" ), ""CITED_FAMILIES_AGG"" AS ( SELECT ""source_family_id"" AS ""family_id"", LISTAGG(DISTINCT ""cited_family_id"", ', ') WITHIN GROUP (ORDER BY ""cited_family_id"") AS ""families_cited"" FROM ""CITED_FAMILIES"" GROUP BY ""source_family_id"" ), ""CITING_PUBS"" AS ( SELECT ""FP"".""family_id"" AS ""target_family_id"", TRIM(""CB"".""VALUE"":""publication_number""::STRING) AS ""citing_pubnum"" FROM ""FAMILY_PUBS"" AS ""FP"" JOIN ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""ABS_AND_EMB"" AS ""A"" ON ""A"".""publication_number"" = ""FP"".""publication_number"", LATERAL FLATTEN(INPUT => ""A"".""cited_by"") AS ""CB"" WHERE TRIM(""CB"".""VALUE"":""publication_number""::STRING) IS NOT NULL AND TRIM(""CB"".""VALUE"":""publication_number""::STRING) != '' ), ""CITING_FAMILIES"" AS ( SELECT DISTINCT ""CP"".""target_family_id"", ""P_ALL"".""family_id"" AS ""citing_family_id"" FROM ""CITING_PUBS"" AS ""CP"" JOIN ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""PUBLICATIONS"" AS ""P_ALL"" ON TRIM(""P_ALL"".""publication_number"") = ""CP"".""citing_pubnum"" WHERE ""P_ALL"".""family_id"" IS NOT NULL AND ""P_ALL"".""family_id"" != ""CP"".""target_family_id"" ), ""CITING_FAMILIES_AGG"" AS ( SELECT ""target_family_id"" AS ""family_id"", LISTAGG(DISTINCT ""citing_family_id"", ', ') WITHIN GROUP (ORDER BY ""citing_family_id"") AS ""families_citing"" FROM ""CITING_FAMILIES"" GROUP BY ""target_family_id"" ) SELECT ""F"".""family_id"", TO_DATE(""F"".""earliest_publication_date_num""::STRING, 'YYYYMMDD') AS ""earliest_publication_date"", COALESCE(""PA"".""publication_numbers"", '') AS ""publication_numbers"", COALESCE(""CA"".""country_codes"", '') AS ""country_codes"", COALESCE(""CC"".""cpc_codes"", '') AS ""cpc_codes"", COALESCE(""IC"".""ipc_codes"", '') AS ""ipc_codes"", COALESCE(""CFA"".""families_cited"", '') AS ""families_cited"", COALESCE(""CIA"".""families_citing"", '') AS ""families_citing"" FROM ""FAMS"" AS ""F"" LEFT JOIN ""PUBS_AGG"" AS ""PA"" ON ""PA"".""family_id"" = ""F"".""family_id"" LEFT JOIN ""COUNTRIES_AGG"" AS ""CA"" ON ""CA"".""family_id"" = ""F"".""family_id"" LEFT JOIN ""CPC_AGG"" AS ""CC"" ON ""CC"".""family_id"" = ""F"".""family_id"" LEFT JOIN ""IPC_AGG"" AS ""IC"" ON ""IC"".""family_id"" = ""F"".""family_id"" LEFT JOIN ""CITED_FAMILIES_AGG"" AS ""CFA"" ON ""CFA"".""family_id"" = ""F"".""family_id"" LEFT JOIN ""CITING_FAMILIES_AGG"" AS ""CIA"" ON ""CIA"".""family_id"" = ""F"".""family_id"" ORDER BY ""F"".""family_id"";",snow,sf_bq127,abs_and_emb.cited_by; abs_and_emb.publication_number; publications.citation; publications.country_code; publications.cpc; publications.family_id; publications.ipc; publications.publication_date; publications.publication_number,9,87,True,fix,True,sf_bq127 sf_bq128,PATENTSVIEW,snowflake,"Retrieve the following information for U.S. patents filed between January 1, 2014, and February 1, 2014. The patent title and abstract. The publication date of the patent. The number of backward citations for each patent (i.e., the number of patents cited by the current patent before its filing date). The number of forward citations for each patent within the first 5 years of its publication (i.e., the number of patents that cited the current patent within 5 years after its publication). For each patent, ensure the forward citations are counted only for citations within 5 years after the publication date, and backward citations are counted for citations before the filing date.","WITH ""filings"" AS ( SELECT ""patent_id"", MIN(TRY_TO_DATE(""date"")) AS ""filing_date"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""APPLICATION"" WHERE ""country"" = 'US' AND TRY_TO_DATE(""date"") IS NOT NULL GROUP BY ""patent_id"" ), ""qualified_cpc"" AS ( SELECT DISTINCT ""patent_id"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""CPC_CURRENT"" WHERE ""subsection_id"" IN ('C05','C06','C07','C08','C09','C10','C11','C12','C13') OR ""group_id"" IN ('A01G','A01H','A61K','A61P','A61Q','B01F','B01J','B81B','B82B','B82Y','G01N','G16H') ), ""base_pats"" AS ( SELECT DISTINCT p.""id"" AS ""patent_id"", p.""title"", p.""abstract"", TRY_TO_DATE(p.""date"") AS ""publication_date"", f.""filing_date"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""PATENT"" p JOIN ""filings"" f ON p.""id"" = f.""patent_id"" JOIN ""qualified_cpc"" qc ON p.""id"" = qc.""patent_id"" WHERE p.""country"" = 'US' AND f.""filing_date"" BETWEEN TO_DATE('2014-01-01') AND TO_DATE('2014-02-01') AND TRY_TO_DATE(p.""date"") IS NOT NULL ), ""backward_counts"" AS ( SELECT bc.""patent_id"", COUNT(DISTINCT bc.""citation_id"") AS ""backward_citations"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""USPATENTCITATION"" bc JOIN ""base_pats"" b ON bc.""patent_id"" = b.""patent_id"" WHERE TRY_TO_DATE(bc.""date"") IS NOT NULL AND TRY_TO_DATE(bc.""date"") < b.""filing_date"" GROUP BY bc.""patent_id"" ), ""forward_counts"" AS ( SELECT fc.""citation_id"" AS ""patent_id"", COUNT(DISTINCT fc.""patent_id"") AS ""forward_citations"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""USPATENTCITATION"" fc JOIN ""base_pats"" b ON fc.""citation_id"" = b.""patent_id"" JOIN ""PATENTSVIEW"".""PATENTSVIEW"".""PATENT"" pc ON pc.""id"" = fc.""patent_id"" WHERE TRY_TO_DATE(pc.""date"") IS NOT NULL AND TRY_TO_DATE(pc.""date"") >= b.""publication_date"" AND TRY_TO_DATE(pc.""date"") <= DATEADD(year, 5, b.""publication_date"") GROUP BY fc.""citation_id"" ) SELECT b.""title"", b.""abstract"", b.""publication_date"", COALESCE(back.""backward_citations"", 0) AS ""backward_citation_count"", COALESCE(fwd.""forward_citations"", 0) AS ""forward_citation_count"" FROM ""base_pats"" b LEFT JOIN ""backward_counts"" back ON back.""patent_id"" = b.""patent_id"" LEFT JOIN ""forward_counts"" fwd ON fwd.""patent_id"" = b.""patent_id"" ORDER BY b.""publication_date"", b.""title""",snow,sf_bq128,application.country; application.date; application.patent_id; cpc_current.group_id; cpc_current.patent_id; cpc_current.subsection_id; patent.abstract; patent.country; patent.date; patent.id; patent.title; uspatentcitation.citation_id; uspatentcitation.date; uspatentcitation.patent_id,14,295,True,fix,True,sf_bq128 sf_bq130,COVID19_NYT,bigquery,"Analyze daily new COVID-19 case counts from March to May 2020, identifying the top five states by daily increases. Please compile a ranking based on how often each state appears in these daily top fives. Then, examine the state that ranks fourth overall and identify its top five counties based on their frequency of appearing in the daily top five new case counts.","WITH StateCases AS ( SELECT b.state_name, b.date, b.confirmed_cases - a.confirmed_cases AS daily_new_cases FROM (SELECT state_name, state_fips_code, confirmed_cases, DATE_ADD(date, INTERVAL 1 DAY) AS date_shift FROM `bigquery-public-data.covid19_nyt.us_states` WHERE date >= '2020-02-29' AND date <= '2020-05-30' ) a JOIN `bigquery-public-data.covid19_nyt.us_states` b ON a.state_fips_code = b.state_fips_code AND a.date_shift = b.date WHERE b.date >= '2020-03-01' AND b.date <= '2020-05-31' ), RankedStatesPerDay AS ( SELECT state_name, date, daily_new_cases, RANK() OVER (PARTITION BY date ORDER BY daily_new_cases DESC) as rank FROM StateCases ), TopStates AS ( SELECT state_name, COUNT(*) AS appearance_count FROM RankedStatesPerDay WHERE rank <= 5 GROUP BY state_name ORDER BY appearance_count DESC ), FourthState AS ( SELECT state_name FROM TopStates LIMIT 1 OFFSET 3 ), CountyCases AS ( SELECT b.county, b.date, b.confirmed_cases - a.confirmed_cases AS daily_new_cases FROM (SELECT county, county_fips_code, confirmed_cases, DATE_ADD(date, INTERVAL 1 DAY) AS date_shift FROM `bigquery-public-data.covid19_nyt.us_counties` WHERE date >= '2020-02-29' AND date <= '2020-05-30' ) a JOIN `bigquery-public-data.covid19_nyt.us_counties` b ON a.county_fips_code = b.county_fips_code AND a.date_shift = b.date WHERE b.date >= '2020-03-01' AND b.date <= '2020-05-31' AND b.state_name = (SELECT state_name FROM FourthState) ), RankedCountiesPerDay AS ( SELECT county, date, daily_new_cases, RANK() OVER (PARTITION BY date ORDER BY daily_new_cases DESC) as rank FROM CountyCases ), TopCounties AS ( SELECT county, COUNT(*) AS appearance_count FROM RankedCountiesPerDay WHERE rank <= 5 GROUP BY county ORDER BY appearance_count DESC LIMIT 5 ) SELECT county FROM TopCounties; ",lite,bq130,us_counties.confirmed_cases; us_counties.county; us_counties.county_fips_code; us_counties.date; us_counties.state_name; us_states.confirmed_cases; us_states.date; us_states.state_fips_code; us_states.state_name,9,29,True,ok,False,bq130 sf_bq143,CPTAC_PDC,bigquery,"Use CPTAC proteomics and RNAseq data for Clear Cell Renal Cell Carcinoma to select 'Primary Tumor' and 'Solid Tissue Normal' samples. Join the datasets on sample submitter IDs and gene symbols. Calculate the correlation between protein abundance (log2 ratio) and gene expression levels (log-transformed+1 FPKM) for each gene and sample type. Filter out correlations with an absolute value greater than 0.5, and compute the average correlation for each sample type.","WITH quant AS ( SELECT meta.sample_submitter_id, meta.sample_type, quant.case_id, quant.aliquot_id, quant.gene_symbol, CAST(quant.protein_abundance_log2ratio AS FLOAT64) AS protein_abundance_log2ratio FROM `isb-cgc-bq.CPTAC.quant_proteome_CPTAC_CCRCC_discovery_study_pdc_current` AS quant JOIN `isb-cgc-bq.PDC_metadata.aliquot_to_case_mapping_current` AS meta ON quant.case_id = meta.case_id AND quant.aliquot_id = meta.aliquot_id AND meta.sample_type IN ('Primary Tumor', 'Solid Tissue Normal') ), gexp AS ( SELECT DISTINCT meta.sample_submitter_id, meta.sample_type, rnaseq.gene_name, LOG(rnaseq.fpkm_unstranded + 1) AS HTSeq__FPKM -- Confirm the correct column name here FROM `isb-cgc-bq.CPTAC.RNAseq_hg38_gdc_current` AS rnaseq JOIN `isb-cgc-bq.PDC_metadata.aliquot_to_case_mapping_current` AS meta ON meta.sample_submitter_id = rnaseq.sample_barcode ), correlation AS ( SELECT quant.gene_symbol, gexp.sample_type, COUNT(*) AS n, CORR(protein_abundance_log2ratio, HTSeq__FPKM) AS corr -- Confirm the correct column name here FROM quant JOIN gexp ON quant.sample_submitter_id = gexp.sample_submitter_id AND gexp.gene_name = quant.gene_symbol AND gexp.sample_type = quant.sample_type GROUP BY quant.gene_symbol, gexp.sample_type ), pval AS ( SELECT gene_symbol, sample_type, n, corr FROM correlation WHERE ABS(corr) <= 0.5 ) SELECT sample_type, AVG(corr) FROM pval GROUP BY sample_type;",lite,bq143,aliquot_to_case_mapping_current.aliquot_id; aliquot_to_case_mapping_current.case_id; aliquot_to_case_mapping_current.sample_submitter_id; aliquot_to_case_mapping_current.sample_type; quant_proteome_*.aliquot_id; quant_proteome_*.case_id; quant_proteome_*.gene_symbol; quant_proteome_*.protein_abundance_log2ratio; rnaseq_hg38_gdc_current.fpkm_unstranded; rnaseq_hg38_gdc_current.gene_name; rnaseq_hg38_gdc_current.sample_barcode,11,710,True,ok,False,bq143 sf_bq144,NCAA_INSIGHTS,bigquery,"Create a dataset by combining NCAA men's basketball tournament game outcomes from the 2014 season onwards, including both the historical tournament games and the 2018 tournament results, with the corresponding pace and efficiency performance metrics for each team and their opponents from the feature_engineering data. The dataset should include the season, game outcome labels (win or loss), team and opponent seeds, school names, pace and efficiency rankings, statistical values, and the differences between the team's and the opponent's metrics to enable a comprehensive analysis of team and opponent dynamics.","WITH outcomes AS ( SELECT season, # 1994 ""win"" AS label, # our label win_seed AS seed, # ranking # this time without seed even win_school_ncaa AS school_ncaa, lose_seed AS opponent_seed, # ranking lose_school_ncaa AS opponent_school_ncaa FROM `data-to-insights.ncaa.mbb_historical_tournament_games` t WHERE season >= 2014 UNION ALL SELECT season, # 1994 ""loss"" AS label, # our label lose_seed AS seed, # ranking lose_school_ncaa AS school_ncaa, win_seed AS opponent_seed, # ranking win_school_ncaa AS opponent_school_ncaa FROM `data-to-insights.ncaa.mbb_historical_tournament_games` t WHERE season >= 2014 UNION ALL SELECT season, label, seed, school_ncaa, opponent_seed, opponent_school_ncaa FROM `data-to-insights.ncaa.2018_tournament_results` ) SELECT o.season, label, seed, school_ncaa, team.pace_rank, team.poss_40min, team.pace_rating, team.efficiency_rank, team.pts_100poss, team.efficiency_rating, opponent_seed, opponent_school_ncaa, opp.pace_rank AS opp_pace_rank, opp.poss_40min AS opp_poss_40min, opp.pace_rating AS opp_pace_rating, opp.efficiency_rank AS opp_efficiency_rank, opp.pts_100poss AS opp_pts_100poss, opp.efficiency_rating AS opp_efficiency_rating, opp.pace_rank - team.pace_rank AS pace_rank_diff, opp.poss_40min - team.poss_40min AS pace_stat_diff, opp.pace_rating - team.pace_rating AS pace_rating_diff, opp.efficiency_rank - team.efficiency_rank AS eff_rank_diff, opp.pts_100poss - team.pts_100poss AS eff_stat_diff, opp.efficiency_rating - team.efficiency_rating AS eff_rating_diff FROM outcomes AS o LEFT JOIN `data-to-insights.ncaa.feature_engineering` AS team ON o.school_ncaa = team.team AND o.season = team.season LEFT JOIN `data-to-insights.ncaa.feature_engineering` AS opp ON o.opponent_school_ncaa = opp.team AND o.season = opp.season",lite,bq144,2018_tournament_results.label; 2018_tournament_results.opponent_school_ncaa; 2018_tournament_results.opponent_seed; 2018_tournament_results.school_ncaa; 2018_tournament_results.season; 2018_tournament_results.seed; feature_engineering.efficiency_rank; feature_engineering.efficiency_rating; feature_engineering.pace_rank; feature_engineering.pace_rating; feature_engineering.poss_40min; feature_engineering.pts_100poss; feature_engineering.season; feature_engineering.team; mbb_historical_tournament_games.lose_school_ncaa; mbb_historical_tournament_games.lose_seed; mbb_historical_tournament_games.season; mbb_historical_tournament_games.win_school_ncaa; mbb_historical_tournament_games.win_seed,19,552,True,ok,False,bq144 sf_bq150,TCGA_HG19_DATA_V0,snowflake,"Assess whether different genetic variants affect the log10-transformed TP53 expression levels in TCGA-BRCA samples using sequencing and mutation data. Provide the total number of samples, the number of mutation types, the mean square between groups, the mean square within groups, and the F-statistic.","with expr as ( select ""sample_barcode"", ln(""normalized_count"") / ln(10) as log_expr from ""TCGA_HG19_DATA_V0"".""TCGA_HG19_DATA_V0"".""RNASEQ_GENE_EXPRESSION_UNC_RSEM"" where ""project_short_name"" = 'TCGA-BRCA' and ""HGNC_gene_symbol"" = 'TP53' and ""normalized_count"" > 0 and substr(""sample_barcode"", 14, 2) = '01' ), mut as ( select ""sample_barcode_tumor"" as sample_barcode, case when count(distinct ""Variant_Classification"") = 1 then max(""Variant_Classification"") else 'Multiple' end as mutation_type from ""TCGA_HG19_DATA_V0"".""TCGA_HG19_DATA_V0"".""SOMATIC_MUTATION_MC3"" where ""project_short_name"" = 'TCGA-BRCA' and ""Hugo_Symbol"" = 'TP53' group by ""sample_barcode_tumor"" ), combined as ( select e.""sample_barcode"", coalesce(m.mutation_type, 'No Mutation') as mutation_type, e.log_expr from expr e left join mut m on e.""sample_barcode"" = m.sample_barcode ), group_stats as ( select mutation_type, count(*) as n_j, avg(log_expr) as mean_j from combined group by mutation_type ), overall as ( select count(*) as N, avg(log_expr) as grand_mean from combined ), ss_between as ( select sum(gs.n_j * power(gs.mean_j - o.grand_mean, 2)) as ssb from group_stats gs cross join overall o ), ss_within as ( select sum(power(c.log_expr - gs.mean_j, 2)) as ssw from combined c join group_stats gs on c.mutation_type = gs.mutation_type ), group_count as ( select count(*) as k from group_stats ) select o.N as total_samples, gc.k as mutation_types, ssb.ssb / nullif(gc.k - 1, 0) as mean_square_between, ssw.ssw / nullif(o.N - gc.k, 0) as mean_square_within, (ssb.ssb / nullif(gc.k - 1, 0)) / (ssw.ssw / nullif(o.N - gc.k, 0)) as f_statistic from overall o cross join group_count gc cross join ss_between ssb cross join ss_within ssw;",snow,sf_bq150,rnaseq_gene_expression_unc_rsem.hgnc_gene_symbol; rnaseq_gene_expression_unc_rsem.normalized_count; rnaseq_gene_expression_unc_rsem.project_short_name; rnaseq_gene_expression_unc_rsem.sample_barcode; somatic_mutation_mc3.hugo_symbol; somatic_mutation_mc3.project_short_name; somatic_mutation_mc3.sample_barcode_tumor; somatic_mutation_mc3.variant_classification,8,233,True,ok,False,sf_bq150 sf_bq151,PANCANCER_ATLAS_2,bigquery,"Using TCGA dataset, calculate the chi-squared statistic to evaluate the association between KRAS and TP53 gene mutations in patients diagnosed with pancreatic adenocarcinoma (PAAD). Incorporate clinical follow-up data and high-quality mutation annotations to accurately determine the frequency of patients with co-occurring KRAS and TP53 mutations compared to those with each mutation occurring independently. Ensure that patient records are meticulously matched based on unique identifiers to maintain data integrity. This analysis aims to identify and quantify potential correlations between KRAS and TP53 genetic alterations within the PAAD patient population.","WITH barcodes AS ( SELECT bcr_patient_barcode AS ParticipantBarcode FROM isb-cgc-bq.pancancer_atlas.Filtered_clinical_PANCAN_patient_with_followup WHERE acronym = 'PAAD' ), table1 AS ( SELECT t1.ParticipantBarcode, IF(t2.ParticipantBarcode IS NULL, 'NO', 'YES') AS data FROM barcodes AS t1 LEFT JOIN ( SELECT ParticipantBarcode AS ParticipantBarcode FROM isb-cgc-bq.pancancer_atlas.Filtered_MC3_MAF_V5_one_per_tumor_sample WHERE Study = 'PAAD' AND Hugo_Symbol = 'KRAS' AND FILTER = 'PASS' GROUP BY ParticipantBarcode ) AS t2 ON t1.ParticipantBarcode = t2.ParticipantBarcode ), table2 AS ( SELECT t1.ParticipantBarcode, IF(t2.ParticipantBarcode IS NULL, 'NO', 'YES') AS data FROM barcodes AS t1 LEFT JOIN ( SELECT ParticipantBarcode AS ParticipantBarcode FROM isb-cgc-bq.pancancer_atlas.Filtered_MC3_MAF_V5_one_per_tumor_sample WHERE Study = 'PAAD' AND Hugo_Symbol = 'TP53' AND FILTER = 'PASS' GROUP BY ParticipantBarcode ) AS t2 ON t1.ParticipantBarcode = t2.ParticipantBarcode ), summ_table AS ( SELECT n1.data AS data1, n2.data AS data2, COUNT(*) AS Nij FROM table1 AS n1 INNER JOIN table2 AS n2 ON n1.ParticipantBarcode = n2.ParticipantBarcode GROUP BY data1, data2 ), contingency_table AS ( SELECT MAX(IF((data1 = 'YES') AND (data2 = 'YES'), Nij, 0)) AS a, MAX(IF((data1 = 'YES') AND (data2 = 'NO'), Nij, 0)) AS b, MAX(IF((data1 = 'NO') AND (data2 = 'YES'), Nij, 0)) AS c, MAX(IF((data1 = 'NO') AND (data2 = 'NO'), Nij, 0)) AS d, (MAX(IF((data1 = 'YES') AND (data2 = 'YES'), Nij, 0)) + MAX(IF((data1 = 'YES') AND (data2 = 'NO'), Nij, 0))) AS row1_total, (MAX(IF((data1 = 'NO') AND (data2 = 'YES'), Nij, 0)) + MAX(IF((data1 = 'NO') AND (data2 = 'NO'), Nij, 0))) AS row2_total, (MAX(IF((data1 = 'YES') AND (data2 = 'YES'), Nij, 0)) + MAX(IF((data1 = 'NO') AND (data2 = 'YES'), Nij, 0))) AS col1_total, (MAX(IF((data1 = 'YES') AND (data2 = 'NO'), Nij, 0)) + MAX(IF((data1 = 'NO') AND (data2 = 'NO'), Nij, 0))) AS col2_total, SUM(Nij) AS grand_total FROM summ_table ) SELECT POWER((a - (row1_total * col1_total) / grand_total), 2) / ((row1_total * col1_total) / grand_total) + POWER((b - (row1_total * col2_total) / grand_total), 2) / ((row1_total * col2_total) / grand_total) + POWER((c - (row2_total * col1_total) / grand_total), 2) / ((row2_total * col1_total) / grand_total) + POWER((d - (row2_total * col2_total) / grand_total), 2) / ((row2_total * col2_total) / grand_total) AS chi_square_statistic FROM contingency_table WHERE a IS NOT NULL AND b IS NOT NULL AND c IS NOT NULL AND d IS NOT NULL; ",lite,bq151,filtered_clinical_pancan_patient_with_followup.acronym; filtered_clinical_pancan_patient_with_followup.bcr_patient_barcode; filtered_mc3_maf_v5_one_per_tumor_sample.filter; filtered_mc3_maf_v5_one_per_tumor_sample.hugo_symbol; filtered_mc3_maf_v5_one_per_tumor_sample.participantbarcode; filtered_mc3_maf_v5_one_per_tumor_sample.study,6,1612,True,ok,False,bq151 sf_bq153,PANCANCER_ATLAS_1,snowflake,"Calculate, for each histology type specified in the 'icd_o_3_histology' field (excluding those enclosed in square brackets), the average of the per-patient average log10(normalized_count + 1) expression levels of the IGF2 gene among LGG patients with valid IGF2 expression data. Match gene expression and clinical data using the ParticipantBarcode field.","WITH PatientAvg AS ( SELECT T1.""bcr_patient_barcode"", T1.""icd_o_3_histology"", AVG(LOG(10, T2.""normalized_count"" + 1)) AS AvgLogExpression FROM ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""CLINICAL_PANCAN_PATIENT_WITH_FOLLOWUP_FILTERED"" AS T1 JOIN ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""EBPP_ADJUSTPANCAN_ILLUMINAHISEQ_RNASEQV2_GENEXP_FILTERED"" AS T2 ON T1.""bcr_patient_barcode"" = T2.""ParticipantBarcode"" WHERE T1.""acronym"" = 'LGG' AND T2.""Symbol"" = 'IGF2' AND T1.""icd_o_3_histology"" IS NOT NULL AND NOT (T1.""icd_o_3_histology"" LIKE '[%' AND T1.""icd_o_3_histology"" LIKE '%]') GROUP BY T1.""bcr_patient_barcode"", T1.""icd_o_3_histology"" ) SELECT ""icd_o_3_histology"", AVG(AvgLogExpression) FROM PatientAvg GROUP BY ""icd_o_3_histology"";",snow,sf_bq153,clinical_pancan_patient_with_followup_filtered.acronym; clinical_pancan_patient_with_followup_filtered.bcr_patient_barcode; clinical_pancan_patient_with_followup_filtered.icd_o_3_histology; ebpp_adjustpancan_illuminahiseq_rnaseqv2_genexp_filtered.normalized_count; ebpp_adjustpancan_illuminahiseq_rnaseqv2_genexp_filtered.participantbarcode; ebpp_adjustpancan_illuminahiseq_rnaseqv2_genexp_filtered.symbol,6,817,True,ok,False,sf_bq153 sf_bq155,TCGA_HG38_DATA_V0,snowflake,"In the TCGA-BRCA cohort of patients who are 80 years old or younger at diagnosis and have a pathological stage of Stage I, Stage II, or Stage IIA, calculate the t-statistic derived from the Pearson correlation between the log10-transformed average RNA-Seq expression levels (using HTSeq__Counts + 1) of the gene SNORA31 and the average microRNA-Seq expression levels of all unique microRNAs, only considering pairs with more than 25 samples and where the absolute Pearson correlation coefficient is between 0.3 and 1.0","WITH FilteredCases AS ( SELECT ""case_barcode"" FROM ""TCGA_HG38_DATA_V0"".""TCGA_BIOCLIN_V0"".""CLINICAL"" WHERE ""project_short_name"" = 'TCGA-BRCA' AND ""age_at_diagnosis"" <= 80 AND ""pathologic_stage"" IN ('Stage I', 'Stage II', 'Stage IIA') ), SNORA31_Expression AS ( SELECT T1.""case_barcode"", LOG(10, AVG(T1.""HTSeq__Counts"") + 1) AS snora31_log_expr FROM ""TCGA_HG38_DATA_V0"".""TCGA_HG38_DATA_V0"".""RNASEQ_GENE_EXPRESSION"" AS T1 INNER JOIN FilteredCases AS T2 ON T1.""case_barcode"" = T2.""case_barcode"" WHERE T1.""gene_name"" = 'SNORA31' GROUP BY T1.""case_barcode"" ), miRNA_Expression AS ( SELECT T1.""case_barcode"", T1.""mirna_id"", AVG(T1.""reads_per_million_miRNA_mapped"") AS mirna_avg_expr FROM ""TCGA_HG38_DATA_V0"".""TCGA_HG38_DATA_V0"".""MIRNASEQ_EXPRESSION"" AS T1 INNER JOIN FilteredCases AS T2 ON T1.""case_barcode"" = T2.""case_barcode"" GROUP BY T1.""case_barcode"", T1.""mirna_id"" ), CorrelationData AS ( SELECT T2.""mirna_id"", CORR(T1.snora31_log_expr, T2.mirna_avg_expr) AS pearson_corr, COUNT(*) AS sample_count FROM SNORA31_Expression AS T1 INNER JOIN miRNA_Expression AS T2 ON T1.""case_barcode"" = T2.""case_barcode"" GROUP BY T2.""mirna_id"" ) SELECT ""mirna_id"", pearson_corr * SQRT((sample_count - 2) / (1 - pearson_corr * pearson_corr)) AS t_statistic FROM CorrelationData WHERE sample_count > 25 AND ABS(pearson_corr) BETWEEN 0.3 AND 1.0",snow,sf_bq155,clinical.age_at_diagnosis; clinical.case_barcode; clinical.pathologic_stage; clinical.project_short_name; mirnaseq_expression.case_barcode; mirnaseq_expression.mirna_id; mirnaseq_expression.reads_per_million_mirna_mapped; rnaseq_gene_expression.case_barcode; rnaseq_gene_expression.gene_name; rnaseq_gene_expression.htseq__counts,10,905,True,fix,True,sf_bq155 sf_bq158,PANCANCER_ATLAS_1,snowflake,Which top five histological types of breast cancer (BRCA) in the PanCancer Atlas exhibit the highest percentage of CDH1 gene mutations?,"WITH clinical_brca AS ( SELECT DISTINCT c.""bcr_patient_barcode"" AS ""ParticipantBarcode"", c.""histological_type"" FROM ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""CLINICAL_PANCAN_PATIENT_WITH_FOLLOWUP_FILTERED"" c WHERE c.""acronym"" = 'BRCA' AND c.""histological_type"" IS NOT NULL ), brca_patients AS ( SELECT DISTINCT m.""ParticipantBarcode"" FROM ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""MC3_MAF_V5_ONE_PER_TUMOR_SAMPLE"" m WHERE m.""Study"" = 'BRCA' ), denom_hist AS ( SELECT p.""ParticipantBarcode"", cb.""histological_type"" FROM brca_patients p JOIN clinical_brca cb ON p.""ParticipantBarcode"" = cb.""ParticipantBarcode"" ), cdh1_mutants AS ( SELECT DISTINCT m.""ParticipantBarcode"" FROM ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""MC3_MAF_V5_ONE_PER_TUMOR_SAMPLE"" m WHERE m.""Study"" = 'BRCA' AND m.""Hugo_Symbol"" = 'CDH1' ) SELECT dh.""histological_type"" AS ""histological_type"", COUNT(DISTINCT CASE WHEN cm.""ParticipantBarcode"" IS NOT NULL THEN dh.""ParticipantBarcode"" END) AS ""mutated_cases"", COUNT(DISTINCT dh.""ParticipantBarcode"") AS ""total_cases"", 100.0 * COUNT(DISTINCT CASE WHEN cm.""ParticipantBarcode"" IS NOT NULL THEN dh.""ParticipantBarcode"" END) / NULLIF(COUNT(DISTINCT dh.""ParticipantBarcode""), 0) AS ""cdh1_mutation_percentage"" FROM denom_hist dh LEFT JOIN cdh1_mutants cm ON dh.""ParticipantBarcode"" = cm.""ParticipantBarcode"" GROUP BY dh.""histological_type"" ORDER BY ""cdh1_mutation_percentage"" DESC LIMIT 5;",snow,sf_bq158,clinical_pancan_patient_with_followup_filtered.acronym; clinical_pancan_patient_with_followup_filtered.bcr_patient_barcode; clinical_pancan_patient_with_followup_filtered.histological_type; mc3_maf_v5_one_per_tumor_sample.hugo_symbol; mc3_maf_v5_one_per_tumor_sample.participantbarcode; mc3_maf_v5_one_per_tumor_sample.study,6,817,True,ok,False,sf_bq158 sf_bq159,PANCANCER_ATLAS_1,snowflake,Calculate the chi-square value to assess the association between histological types and the presence of CDH1 gene mutations in BRCA patients using data from the PanCancer Atlas. Focus on patients with known histological types and consider only reliable mutation entries. Exclude any histological types or mutation statuses with marginal totals less than or equal to 10. Match clinical and mutation data using ParticipantBarcode,"WITH Cdh1MutatedPatients AS ( SELECT DISTINCT ""ParticipantBarcode"" FROM ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""MC3_MAF_V5_ONE_PER_TUMOR_SAMPLE"" WHERE ""Hugo_Symbol"" = 'CDH1' AND ""FILTER"" = 'PASS' ), PatientData AS ( SELECT T1.""histological_type"", CASE WHEN T2.""ParticipantBarcode"" IS NOT NULL THEN 'mutated' ELSE 'not_mutated' END AS mutation_status FROM ""PANCANCER_ATLAS_1"".""PANCANCER_ATLAS_FILTERED"".""CLINICAL_PANCAN_PATIENT_WITH_FOLLOWUP_FILTERED"" AS T1 LEFT JOIN Cdh1MutatedPatients AS T2 ON T1.""bcr_patient_barcode"" = T2.""ParticipantBarcode"" WHERE T1.""acronym"" = 'BRCA' AND T1.""histological_type"" IS NOT NULL ), InitialContingency AS ( SELECT ""histological_type"", mutation_status, COUNT(*) AS observed FROM PatientData GROUP BY ""histological_type"", mutation_status ), FilteredContingency AS ( SELECT ""histological_type"", mutation_status, observed FROM InitialContingency WHERE ""histological_type"" IN ( SELECT ""histological_type"" FROM InitialContingency GROUP BY ""histological_type"" HAVING SUM(observed) > 10 ) AND mutation_status IN ( SELECT mutation_status FROM InitialContingency GROUP BY mutation_status HAVING SUM(observed) > 10 ) ), ChiSquareInput AS ( SELECT ""histological_type"", mutation_status, observed, SUM(observed) OVER (PARTITION BY ""histological_type"") AS row_total, SUM(observed) OVER (PARTITION BY mutation_status) AS col_total, SUM(observed) OVER () AS grand_total FROM FilteredContingency ) SELECT SUM(POWER(observed - (row_total * col_total / grand_total), 2) / (row_total * col_total / grand_total)) FROM ChiSquareInput;",snow,sf_bq159,clinical_pancan_patient_with_followup_filtered.acronym; clinical_pancan_patient_with_followup_filtered.bcr_patient_barcode; clinical_pancan_patient_with_followup_filtered.histological_type; mc3_maf_v5_one_per_tumor_sample.filter; mc3_maf_v5_one_per_tumor_sample.hugo_symbol; mc3_maf_v5_one_per_tumor_sample.participantbarcode,6,817,True,ok,False,sf_bq159 sf_bq161,PANCANCER_ATLAS_2,bigquery,"Calculate the net difference between the number of pancreatic adenocarcinoma (PAAD) patients in TCGA's dataset who are confirmed to have mutations in both KRAS and TP53 genes, and those without mutations in either gene. Utilize patient clinical and follow-up data alongside genomic mutation details from TCGA’s cancer genomics database, focusing specifically on PAAD studies where the mutations have passed quality filters.","WITH barcodes AS ( SELECT bcr_patient_barcode AS ParticipantBarcode FROM `isb-cgc-bq.pancancer_atlas.Filtered_clinical_PANCAN_patient_with_followup` WHERE acronym = 'PAAD' ) ,table1 AS ( SELECT t1.ParticipantBarcode, IF( t2.ParticipantBarcode is null, 'NO', 'YES') as data FROM barcodes AS t1 LEFT JOIN ( SELECT ParticipantBarcode AS ParticipantBarcode FROM `isb-cgc-bq.pancancer_atlas.Filtered_MC3_MAF_V5_one_per_tumor_sample` WHERE Study = 'PAAD' AND Hugo_Symbol = 'KRAS' AND FILTER = 'PASS' GROUP BY ParticipantBarcode ) AS t2 ON t1.ParticipantBarcode = t2.ParticipantBarcode ) ,table2 AS ( SELECT t1.ParticipantBarcode, IF( t2.ParticipantBarcode is null, 'NO', 'YES') as data FROM barcodes AS t1 LEFT JOIN ( SELECT ParticipantBarcode AS ParticipantBarcode FROM `isb-cgc-bq.pancancer_atlas.Filtered_MC3_MAF_V5_one_per_tumor_sample` WHERE Study = 'PAAD' AND Hugo_Symbol = 'TP53' AND FILTER = 'PASS' GROUP BY ParticipantBarcode ) AS t2 ON t1.ParticipantBarcode = t2.ParticipantBarcode ), INFO AS ( SELECT n1.data as data1, n2.data as data2, COUNT(*) as Nij FROM table1 AS n1 INNER JOIN table2 AS n2 ON n1.ParticipantBarcode = n2.ParticipantBarcode GROUP BY data1, data2 ) SELECT (SELECT Nij FROM INFO WHERE data1=""YES"" AND data2=""YES"") - (SELECT Nij FROM INFO WHERE data1=""NO"" AND data2=""NO"") ",lite,bq161,filtered_clinical_pancan_patient_with_followup.acronym; filtered_clinical_pancan_patient_with_followup.bcr_patient_barcode; filtered_mc3_maf_v5_one_per_tumor_sample.filter; filtered_mc3_maf_v5_one_per_tumor_sample.hugo_symbol; filtered_mc3_maf_v5_one_per_tumor_sample.participantbarcode; filtered_mc3_maf_v5_one_per_tumor_sample.study,6,1612,True,ok,False,bq161 sf_bq166,TCGA_MITELMAN,snowflake,"Using segment-level copy number data from the copy_number_segment_allelic_hg38_gdc_r23 dataset restricted to 'TCGA-KIRC' samples, merge these segments with the cytogenetic band definitions in 'CytoBands_hg38' to identify each sample’s maximum copy number per cytoband. Classify these maximum copy numbers into amplifications (>3), gains (=3), homozygous deletions (=0), heterozygous deletions (=1), or normal (=2), then calculate the frequency of each subtype out of the total number of distinct cases, and finally present these frequencies as percentages sorted by chromosome and cytoband.","WITH ""kirc_total"" AS ( SELECT COUNT(DISTINCT ""case_barcode"") AS ""total_cases"" FROM ""TCGA_MITELMAN"".""TCGA_VERSIONED"".""COPY_NUMBER_SEGMENT_ALLELIC_HG38_GDC_R23"" WHERE ""project_short_name"" = 'TCGA-KIRC' ), ""seg_band"" AS ( SELECT s.""case_barcode"", s.""sample_barcode"", s.""chromosome"", b.""cytoband_name"", s.""copy_number"" FROM ""TCGA_MITELMAN"".""TCGA_VERSIONED"".""COPY_NUMBER_SEGMENT_ALLELIC_HG38_GDC_R23"" s JOIN ""TCGA_MITELMAN"".""PROD"".""CYTOBANDS_HG38"" b ON s.""chromosome"" = b.""chromosome"" AND LEAST(s.""end_pos"", b.""hg38_stop"") - GREATEST(s.""start_pos"", b.""hg38_start"") > 0 WHERE s.""project_short_name"" = 'TCGA-KIRC' ), ""sample_band_max"" AS ( SELECT ""case_barcode"", ""sample_barcode"", ""chromosome"", ""cytoband_name"", MAX(""copy_number"") AS ""sample_max_copy"" FROM ""seg_band"" GROUP BY ""case_barcode"", ""sample_barcode"", ""chromosome"", ""cytoband_name"" ), ""case_band_max"" AS ( SELECT ""case_barcode"", ""chromosome"", ""cytoband_name"", MAX(""sample_max_copy"") AS ""case_max_copy"" FROM ""sample_band_max"" GROUP BY ""case_barcode"", ""chromosome"", ""cytoband_name"" ), ""case_band_category"" AS ( SELECT ""case_barcode"", ""chromosome"", ""cytoband_name"", CASE WHEN ""case_max_copy"" > 3 THEN 'Amplification' WHEN ""case_max_copy"" = 3 THEN 'Gain' WHEN ""case_max_copy"" = 2 THEN 'Normal' WHEN ""case_max_copy"" = 1 THEN 'Heterozygous Deletion' WHEN ""case_max_copy"" = 0 THEN 'Homozygous Deletion' ELSE 'Unknown' END AS ""category"" FROM ""case_band_max"" ), ""band_counts"" AS ( SELECT ""chromosome"", ""cytoband_name"", SUM(CASE WHEN ""category"" = 'Amplification' THEN 1 ELSE 0 END) AS ""n_amplification"", SUM(CASE WHEN ""category"" = 'Gain' THEN 1 ELSE 0 END) AS ""n_gain"", SUM(CASE WHEN ""category"" = 'Homozygous Deletion' THEN 1 ELSE 0 END) AS ""n_homdel"", SUM(CASE WHEN ""category"" = 'Heterozygous Deletion' THEN 1 ELSE 0 END) AS ""n_hetdel"", SUM(CASE WHEN ""category"" = 'Normal' THEN 1 ELSE 0 END) AS ""n_normal"" FROM ""case_band_category"" GROUP BY ""chromosome"", ""cytoband_name"" ) SELECT bc.""chromosome"", bc.""cytoband_name"", 100.0 * bc.""n_amplification"" / kt.""total_cases"" AS ""amplification_pct"", 100.0 * bc.""n_gain"" / kt.""total_cases"" AS ""gain_pct"", 100.0 * bc.""n_homdel"" / kt.""total_cases"" AS ""homozygous_deletion_pct"", 100.0 * bc.""n_hetdel"" / kt.""total_cases"" AS ""heterozygous_deletion_pct"", 100.0 * bc.""n_normal"" / kt.""total_cases"" AS ""normal_pct"" FROM ""band_counts"" bc CROSS JOIN ""kirc_total"" kt ORDER BY CASE WHEN REGEXP_LIKE(REGEXP_REPLACE(bc.""chromosome"", '^chr', ''), '^[0-9]+$') THEN TO_NUMBER(REGEXP_REPLACE(bc.""chromosome"", '^chr', '')) WHEN REGEXP_REPLACE(bc.""chromosome"", '^chr', '') = 'X' THEN 23 WHEN REGEXP_REPLACE(bc.""chromosome"", '^chr', '') = 'Y' THEN 24 ELSE 25 END, bc.""cytoband_name"";",snow,sf_bq166,copy_number_segment_allelic_hg38_gdc_r23.case_barcode; copy_number_segment_allelic_hg38_gdc_r23.chromosome; copy_number_segment_allelic_hg38_gdc_r23.copy_number; copy_number_segment_allelic_hg38_gdc_r23.end_pos; copy_number_segment_allelic_hg38_gdc_r23.project_short_name; copy_number_segment_allelic_hg38_gdc_r23.sample_barcode; copy_number_segment_allelic_hg38_gdc_r23.start_pos; cytobands_hg38.chromosome; cytobands_hg38.cytoband_name; cytobands_hg38.hg38_start; cytobands_hg38.hg38_stop,11,2500,True,fix,False,sf_bq166 sf_bq167,META_KAGGLE,snowflake,"Identify the pair of Kaggle users involved in ForumMessageVotes such that one user has given the other the greatest distinct number of upvotes, then also display how many upvotes that recipient returned. Present the usernames of both users, the total distinct upvotes one received from the other, and the upvotes they gave back, sorting by the highest received count and then by the highest given count, and show only the top result.","WITH ""DIRECTED"" AS ( SELECT ""v"".""FromUserId"" AS ""FROM_USER_ID"", ""v"".""ToUserId"" AS ""TO_USER_ID"", COUNT(DISTINCT ""v"".""ForumMessageId"") AS ""RECEIVED_CNT"" FROM ""META_KAGGLE"".""META_KAGGLE"".""FORUMMESSAGEVOTES"" AS ""v"" WHERE ""v"".""FromUserId"" IS NOT NULL AND ""v"".""ToUserId"" IS NOT NULL AND ""v"".""FromUserId"" != ""v"".""ToUserId"" GROUP BY ""v"".""FromUserId"", ""v"".""ToUserId"" ) SELECT COALESCE(""u_from"".""UserName"", ""u_from"".""DisplayName"") AS ""GiverUserName"", COALESCE(""u_to"".""UserName"", ""u_to"".""DisplayName"") AS ""ReceiverUserName"", ""d"".""RECEIVED_CNT"" AS ""ReceivedUpvotes"", COALESCE(""d2"".""RECEIVED_CNT"", 0) AS ""ReturnedUpvotes"" FROM ""DIRECTED"" AS ""d"" LEFT JOIN ""DIRECTED"" AS ""d2"" ON ""d2"".""FROM_USER_ID"" = ""d"".""TO_USER_ID"" AND ""d2"".""TO_USER_ID"" = ""d"".""FROM_USER_ID"" LEFT JOIN ""META_KAGGLE"".""META_KAGGLE"".""USERS"" AS ""u_from"" ON ""u_from"".""Id"" = ""d"".""FROM_USER_ID"" LEFT JOIN ""META_KAGGLE"".""META_KAGGLE"".""USERS"" AS ""u_to"" ON ""u_to"".""Id"" = ""d"".""TO_USER_ID"" ORDER BY ""d"".""RECEIVED_CNT"" DESC, COALESCE(""d2"".""RECEIVED_CNT"", 0) DESC FETCH FIRST 1 ROWS ONLY;",snow,sf_bq167,forummessagevotes.forummessageid; forummessagevotes.fromuserid; forummessagevotes.touserid; users.displayname; users.id; users.username,6,237,True,ok,False,sf_bq167 sf_bq172,CMS_DATA,bigquery,"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. ","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;",lite,bq172,part_d_prescriber_2014.drug_name; part_d_prescriber_2014.nppes_provider_state; part_d_prescriber_2014.total_claim_count; part_d_prescriber_2014.total_drug_cost,4,694,True,fix,False,bq172 sf_bq176,TCGA_MITELMAN,snowflake,"Identify the case barcodes from the TCGA-LAML study with the highest weighted average copy number in cytoband 15q11 on chromosome 15, using segment data and cytoband overlaps from TCGA's genomic and Mitelman databases.","/* Goal: Identify TCGA-LAML case barcodes with the highest weighted average copy number inside cytoband 15q11 (chr15:19,000,000-25,500,000 on hg38). ‑ Use cytoband coordinates from CYTOBANDS_HG38. ‑ Use segment-level copy number from COPY_NUMBER_SEGMENT_ALLELIC_HG38_GDC_R23 (this table stores integer ""copy_number"" values and chromosome names like 'chr15'). ‑ Weighted average = Σ(copy_number * overlap_length) / Σ(overlap_length), where overlap_length is the number of bases of a segment that fall inside 15q11. ‑ Return the barcode(s) whose weighted average equals the global maximum. */ WITH band AS ( /* Exact genomic span of cytoband 15q11 on chr15 (hg38) */ SELECT MIN(""hg38_start"") AS ""region_start"", MAX(""hg38_stop"") AS ""region_end"" FROM ""TCGA_MITELMAN"".""PROD"".""CYTOBANDS_HG38"" WHERE ""cytoband_name"" ILIKE '15q11%' -- include 15q11, 15q11.1, 15q11.2, ... AND ""chromosome"" = 'chr15' ), laml_segments AS ( /* All chr15 copy-number segments for TCGA-LAML cases (hg38, allelic table) */ SELECT s.""case_barcode"", s.""start_pos"", s.""end_pos"", s.""copy_number"" FROM ""TCGA_MITELMAN"".""TCGA_VERSIONED"".""COPY_NUMBER_SEGMENT_ALLELIC_HG38_GDC_R23"" s WHERE s.""project_short_name"" = 'TCGA-LAML' AND s.""chromosome"" = 'chr15' ), overlaps AS ( /* Keep only segment portions that actually overlap 15q11 */ SELECT l.""case_barcode"", GREATEST(l.""start_pos"", b.""region_start"") AS ""ov_start"", LEAST(l.""end_pos"", b.""region_end"") AS ""ov_end"", l.""copy_number"" FROM laml_segments l CROSS JOIN band b WHERE l.""end_pos"" >= b.""region_start"" -- segment starts before region end AND l.""start_pos"" <= b.""region_end"" -- segment ends after region start ), weighted AS ( /* Compute weighted sums per case */ SELECT ""case_barcode"", SUM( (""ov_end"" - ""ov_start"" + 1) * ""copy_number"" ) AS ""weighted_sum"", SUM( ""ov_end"" - ""ov_start"" + 1 ) AS ""total_len"" FROM overlaps GROUP BY ""case_barcode"" ), per_case AS ( /* Final weighted average copy number per case */ SELECT ""case_barcode"", ""weighted_sum"" / ""total_len"" AS ""weighted_avg_copy_number"" FROM weighted ) /* Return the barcode(s) with the highest weighted average */ SELECT ""case_barcode"" FROM per_case WHERE ""weighted_avg_copy_number"" = ( SELECT MAX(""weighted_avg_copy_number"") FROM per_case ) ORDER BY ""case_barcode"";",snow,sf_bq176,copy_number_segment_allelic_hg38_gdc_r23.case_barcode; copy_number_segment_allelic_hg38_gdc_r23.chromosome; copy_number_segment_allelic_hg38_gdc_r23.copy_number; copy_number_segment_allelic_hg38_gdc_r23.end_pos; copy_number_segment_allelic_hg38_gdc_r23.project_short_name; copy_number_segment_allelic_hg38_gdc_r23.start_pos; cytobands_hg38.chromosome; cytobands_hg38.cytoband_name; cytobands_hg38.hg38_start; cytobands_hg38.hg38_stop,10,2500,True,ok,False,sf_bq176 sf_bq182,GITHUB_REPOS_DATE,snowflake,"Which primary programming languages, determined by the highest number of bytes in each repository, had at least 5 PullRequestEvents on January 18, 2023 across all their repositories?","WITH primary_languages AS ( SELECT ""repo_name"", lang_data.value:""name""::string as primary_language, ROW_NUMBER() OVER (PARTITION BY ""repo_name"" ORDER BY lang_data.value:""bytes""::int DESC) as rn FROM GITHUB_REPOS_DATE.GITHUB_REPOS.LANGUAGES, TABLE(FLATTEN(PARSE_JSON(""language""))) as lang_data WHERE ""language"" != '[]' ), primary_lang_only AS ( SELECT ""repo_name"", primary_language FROM primary_languages WHERE rn = 1 ), pull_requests_jan18 AS ( SELECT ""repo"":""name""::string as repo_name, COUNT(*) as pr_count FROM GITHUB_REPOS_DATE.YEAR._2023 WHERE ""type"" = 'PullRequestEvent' AND ""created_at"" >= 1674009600000000 -- 2023-01-18 00:00:00 UTC AND ""created_at"" < 1674096000000000 -- 2023-01-19 00:00:00 UTC GROUP BY ""repo"":""name""::string ) SELECT plo.primary_language, SUM(pr.pr_count) as total_pr_events FROM primary_lang_only plo JOIN pull_requests_jan18 pr ON plo.""repo_name"" = pr.repo_name GROUP BY plo.primary_language HAVING total_pr_events >= 5 ORDER BY total_pr_events DESC",snow,sf_bq182,_20_*.created_at; _20_*.repo; _20_*.type; languages.language; languages.repo_name,5,43,True,ok,False,sf_bq182 sf_bq185,NEW_YORK_PLUS,bigquery,"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?","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""; ",lite,bq185,taxi_zone_geom.borough; taxi_zone_geom.zone_id; tlc_yellow_trips_*.dropoff_datetime; tlc_yellow_trips_*.dropoff_location_id; tlc_yellow_trips_*.passenger_count; tlc_yellow_trips_*.pickup_datetime; tlc_yellow_trips_*.pickup_location_id; tlc_yellow_trips_*.trip_distance,8,435,True,ok,False,bq185 sf_bq187,ETHEREUM_BLOCKCHAIN,snowflake,"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.","WITH inflows AS ( SELECT ""to_address"" AS address, SUM(CAST(""value"" AS NUMBER)) AS total_received FROM ""ETHEREUM_BLOCKCHAIN"".""ETHEREUM_BLOCKCHAIN"".""TOKEN_TRANSFERS"" WHERE ""token_address"" = '0xb8c77482e45f1f44de1745f52c74426c631bdd52' AND ""to_address"" != '0x0000000000000000000000000000000000000000' GROUP BY ""to_address"" ), outflows AS ( SELECT ""from_address"" AS address, SUM(CAST(""value"" AS NUMBER)) AS total_sent FROM ""ETHEREUM_BLOCKCHAIN"".""ETHEREUM_BLOCKCHAIN"".""TOKEN_TRANSFERS"" WHERE ""token_address"" = '0xb8c77482e45f1f44de1745f52c74426c631bdd52' AND ""from_address"" != '0x0000000000000000000000000000000000000000' GROUP BY ""from_address"" ), all_addresses AS ( SELECT address FROM inflows UNION SELECT address FROM outflows ), net_balances AS ( SELECT aa.address, COALESCE(i.total_received, 0) - COALESCE(o.total_sent, 0) AS balance FROM all_addresses aa LEFT JOIN inflows i ON aa.address = i.address LEFT JOIN outflows o ON aa.address = o.address ) SELECT SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END) / POWER(10, 18) AS total_circulating_supply FROM net_balances",snow,sf_bq187,token_transfers.from_address; token_transfers.to_address; token_transfers.token_address; token_transfers.value,4,88,True,ok,False,sf_bq187 sf_bq193,GITHUB_REPOS,snowflake,"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.","WITH readme_lines AS ( SELECT sc.""sample_repo_name"" AS ""repo_name"", TRIM(REPLACE(l.value::string, '\r', '')) AS ""line_clean"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""SAMPLE_CONTENTS"" sc, LATERAL FLATTEN(input => SPLIT(sc.""content"", '\n')) l WHERE sc.""sample_path"" ILIKE '%README.md' AND NVL(sc.""binary"", FALSE) = FALSE AND sc.""content"" IS NOT NULL ), filtered_lines AS ( SELECT rl.""repo_name"", rl.""line_clean"" FROM readme_lines rl WHERE rl.""line_clean"" != '' AND LTRIM(rl.""line_clean"") NOT LIKE '#%' AND LTRIM(rl.""line_clean"") NOT LIKE '//%' ), repo_languages AS ( SELECT lg.""repo_name"", TRIM(fl.value:""name""::string) AS ""language_name"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""LANGUAGES"" lg, LATERAL FLATTEN(input => lg.""language"") fl WHERE fl.value:""name"" IS NOT NULL AND TRIM(fl.value:""name""::string) != '' ) SELECT f.""line_clean"" AS ""line"", COUNT(DISTINCT f.""repo_name"") AS ""frequency"", LISTAGG(DISTINCT rl.""language_name"", ', ') WITHIN GROUP (ORDER BY rl.""language_name"") AS ""languages"" FROM filtered_lines f LEFT JOIN repo_languages rl ON rl.""repo_name"" = f.""repo_name"" GROUP BY f.""line_clean"" ORDER BY ""frequency"" DESC, ""line"" ASC",snow,sf_bq193,languages.language; languages.repo_name; sample_contents.binary; sample_contents.content; sample_contents.sample_path; sample_contents.sample_repo_name,6,34,True,ok,False,sf_bq193 sf_bq198,NCAA_BASKETBALL,bigquery,"List the top 5 universities with the most seasons where they achieved the maximum wins in their respective NCAA basketball seasons between 1900-2000, showing each team's total number of such peak-performance seasons, while excluding entries with missing team names.","SELECT team_name, COUNT(*) AS top_performer_count FROM ( SELECT DISTINCT c2.season, c2.market AS team_name FROM ( SELECT season AS a, MAX(wins) AS win_max FROM `bigquery-public-data.ncaa_basketball.mbb_historical_teams_seasons` WHERE season<=2000 AND season >=1900 GROUP BY season ), `bigquery-public-data.ncaa_basketball.mbb_historical_teams_seasons` c2 WHERE win_max = c2.wins AND a = c2.season AND c2.market IS NOT NULL ORDER BY c2.season) GROUP BY team_name ORDER BY top_performer_count DESC, team_name LIMIT 5",lite,bq198,mbb_historical_teams_seasons.market; mbb_historical_teams_seasons.season; mbb_historical_teams_seasons.wins,3,505,True,ok,False,bq198 sf_bq199,IOWA_LIQUOR_SALES,bigquery,"Identify the top 10 liquor categories in Iowa in 2021 by calculating, for each category, the average of the per-liter retail prices across all sales transactions in that category during 2021. For these top categories, provide their average per-liter retail prices calculated in the same manner for the years 2019, 2020, and 2021.","WITH price_2020 AS ( SELECT category_name AS category, AVG(state_bottle_retail / (bottle_volume_ml / 1000)) AS avg_price_liter_2020 FROM `bigquery-public-data.iowa_liquor_sales.sales` WHERE bottle_volume_ml > 0 AND EXTRACT(YEAR FROM date) = 2020 GROUP BY category ), price_2019 AS ( SELECT category_name AS category, AVG(state_bottle_retail / (bottle_volume_ml / 1000)) AS avg_price_liter_2019 FROM `bigquery-public-data.iowa_liquor_sales.sales` WHERE bottle_volume_ml > 0 AND EXTRACT(YEAR FROM date) = 2019 GROUP BY category ), price_2021 AS ( SELECT category_name AS category, AVG(state_bottle_retail / (bottle_volume_ml / 1000)) AS avg_price_liter_2021 FROM `bigquery-public-data.iowa_liquor_sales.sales` WHERE bottle_volume_ml > 0 AND EXTRACT(YEAR FROM date) = 2021 GROUP BY category ) SELECT price_2021.category, price_2019.avg_price_liter_2019, price_2020.avg_price_liter_2020, price_2021.avg_price_liter_2021 FROM price_2021 LEFT JOIN price_2019 ON price_2021.category = price_2019.category LEFT JOIN price_2020 ON price_2021.category = price_2020.category ORDER BY price_2021.avg_price_liter_2021 DESC LIMIT 10;",lite,bq199,sales.bottle_volume_ml; sales.category_name; sales.date; sales.state_bottle_retail,4,48,True,fix,True,bq199 sf_bq203,NEW_YORK_PLUS,bigquery,"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?","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",lite,bq203,station_entrances.ada_compliant; station_entrances.entry; station_entrances.station_name; stations.borough_name; stations.station_name,5,435,True,ok,False,bq203 sf_bq204,ECLIPSE_MEGAMOVIE,bigquery,Find the user with the highest total clicks across all records from all available photo collections.,"SELECT user FROM ( Select user From `bigquery-public-data.eclipse_megamovie.photos_v_0_1` UNION ALL Select user From`bigquery-public-data.eclipse_megamovie.photos_v_0_2` UNION ALL Select user From`bigquery-public-data.eclipse_megamovie.photos_v_0_3` ) GROUP BY user HAVING COUNT (user)=( SELECT MAX(mycount) FROM ( SELECT user, COUNT(user) mycount FROM ( Select user From `bigquery-public-data.eclipse_megamovie.photos_v_0_1` UNION ALL Select user From`bigquery-public-data.eclipse_megamovie.photos_v_0_2` UNION ALL Select user From`bigquery-public-data.eclipse_megamovie.photos_v_0_3` ) GROUP BY user)) ORDER BY COUNT(user) LIMIT 1",lite,bq204,photos_v_0_*.user; photos_v_0_3.user,2,105,True,ok,False,bq204 sf_bq209,PATENTS,snowflake,"Can you calculate the number of utility patents that were granted in 2010 and have exactly one forward citation within a 10-year window following their application/filing date? For this analysis, forward citations should be counted as distinct citing application numbers that cited the patent within 10 years after the patent's own filing date.","WITH temp_view_2 AS ( SELECT ""publication_number"", ""application_number"", ""filing_date"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" WHERE ""application_kind"" = 'A' AND ""grant_date"" >= 20100101 AND ""grant_date"" <= 20101231 ), citations_parsed AS ( SELECT p.""publication_number"" AS citing_patent, c.value:publication_number::STRING AS cited_patent FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p, LATERAL FLATTEN(input => p.""citation"") c WHERE p.""citation"" IS NOT NULL AND c.value:publication_number::STRING IS NOT NULL AND c.value:publication_number::STRING != '' ), temp_view_6 AS ( SELECT cp.citing_patent, cp.cited_patent, tv2.""application_number"", tv2.""filing_date"" FROM citations_parsed cp INNER JOIN temp_view_2 tv2 ON cp.cited_patent = tv2.""publication_number"" ), temp_view_7 AS ( SELECT tv6.cited_patent, COUNT(DISTINCT p_citing.""application_number"") AS distinct_citing_applications FROM temp_view_6 tv6 INNER JOIN ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p_citing ON tv6.citing_patent = p_citing.""publication_number"" WHERE p_citing.""filing_date"" >= tv6.""filing_date"" AND p_citing.""filing_date"" <= tv6.""filing_date"" + 100000 GROUP BY tv6.cited_patent ) SELECT COUNT(*) AS patents_with_exactly_one_citation FROM temp_view_7 WHERE distinct_citing_applications = 1",snow,sf_bq209,publications.application_kind; publications.application_number; publications.citation; publications.filing_date; publications.grant_date; publications.publication_number,6,79,True,ok,False,sf_bq209 sf_bq210,PATENTS,snowflake,How many US B2 patents granted between 2008 and 2018 contain claims that do not include the word 'claim'?,"SELECT COUNT(*) AS ""num_patents"" FROM ( SELECT p.""publication_number"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" AS p, LATERAL FLATTEN(input => p.""claims_localized"") AS cl WHERE p.""country_code"" = 'US' AND p.""kind_code"" = 'B2' AND p.""grant_date"" BETWEEN 20080101 AND 20181231 GROUP BY p.""publication_number"" HAVING SUM(CASE WHEN REGEXP_LIKE(cl.value:""text""::string, '\\bclaim\\b', 'i') THEN 1 ELSE 0 END) = 0 );",snow,sf_bq210,publications.claims_localized; publications.country_code; publications.grant_date; publications.kind_code; publications.publication_number,5,79,True,ok,False,sf_bq210 sf_bq213,PATENTS,snowflake,What is the most common 4-digit IPC code among US B2 utility patents granted from June to August in 2022?,"WITH ""filtered"" AS ( SELECT p.""publication_number"", p.""ipc"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p WHERE p.""country_code"" = 'US' AND p.""kind_code"" = 'B2' AND p.""grant_date"" BETWEEN 20220601 AND 20220831 ), ""flat"" AS ( SELECT fpub.""publication_number"", SUBSTRING(f.value:""code""::string, 1, 4) AS ""ipc4"", CASE WHEN f.value:""first""::boolean = TRUE THEN 1 ELSE 0 END AS ""is_first"" FROM ""filtered"" fpub, LATERAL FLATTEN(input => fpub.""ipc"") f WHERE f.value:""code"" IS NOT NULL AND SUBSTRING(f.value:""code""::string, 1, 4) <> '' ), ""agg"" AS ( SELECT ""publication_number"", ""ipc4"", COUNT(*) AS ""cnt_all"", MAX(""is_first"") AS ""has_first"" FROM ""flat"" GROUP BY ""publication_number"", ""ipc4"" ), ""ranked"" AS ( SELECT ""publication_number"", ""ipc4"", ROW_NUMBER() OVER ( PARTITION BY ""publication_number"" ORDER BY ""has_first"" DESC, ""cnt_all"" DESC, ""ipc4"" ASC ) AS ""rn"" FROM ""agg"" ) SELECT ""ipc4"" AS ""most_common_ipc4"", COUNT(*) AS ""num_publications"" FROM ""ranked"" WHERE ""rn"" = 1 GROUP BY ""ipc4"" ORDER BY ""num_publications"" DESC, ""ipc4"" ASC LIMIT 1;",snow,sf_bq213,publications.country_code; publications.grant_date; publications.ipc; publications.kind_code; publications.publication_number,5,79,True,ok,False,sf_bq213 sf_bq216,PATENTS_GOOGLE,snowflake,Identify the top five patents filed in the same year as `US-9741766-B2` that are most similar to it based on technological similarities. Please provide the publication numbers.,"WITH target_embedding_flat AS ( SELECT f.index, f.value::FLOAT AS value FROM ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""ABS_AND_EMB"" AS t, LATERAL FLATTEN(input => t.""embedding_v1"") AS f WHERE t.""publication_number"" = 'US-9741766-B2' ), candidate_patents_with_year AS ( SELECT p.""publication_number"", e.""embedding_v1"" FROM ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""PUBLICATIONS"" AS p JOIN ""PATENTS_GOOGLE"".""PATENTS_GOOGLE"".""ABS_AND_EMB"" AS e ON p.""publication_number"" = e.""publication_number"" WHERE p.""filing_date"" != 0 AND EXTRACT(YEAR FROM TO_DATE(CAST(p.""filing_date"" AS VARCHAR), 'YYYYMMDD')) = 2016 AND p.""publication_number"" != 'US-9741766-B2' ), candidate_embeddings_flat AS ( SELECT c.""publication_number"", f.index, f.value::FLOAT AS value FROM candidate_patents_with_year AS c, LATERAL FLATTEN(input => c.""embedding_v1"") AS f ) SELECT c.""publication_number"" FROM candidate_embeddings_flat AS c JOIN target_embedding_flat AS t ON c.index = t.index GROUP BY c.""publication_number"" ORDER BY SUM(c.value * t.value) DESC LIMIT 5",snow,sf_bq216,abs_and_emb.embedding_v1; abs_and_emb.publication_number; publications.filing_date; publications.publication_number,4,87,True,ok,False,sf_bq216 sf_bq218,IOWA_LIQUOR_SALES,bigquery,What are the top 5 items with the highest year-over-year growth percentage in total sales revenue for the year 2023?,"WITH AnnualSales AS ( SELECT item_description, EXTRACT(YEAR FROM date) AS year, SUM(sale_dollars) AS total_sales_revenue, COUNT(DISTINCT invoice_and_item_number) AS unique_purchases FROM `bigquery-public-data.iowa_liquor_sales.sales` WHERE EXTRACT(YEAR FROM date) IN (2022, 2023) AND item_description IS NOT NULL AND sale_dollars IS NOT NULL GROUP BY item_description, year ), YoYGrowth AS ( SELECT curr.item_description, curr.year, curr.total_sales_revenue, curr.unique_purchases, LAG(curr.total_sales_revenue) OVER(PARTITION BY curr.item_description ORDER BY curr.year) AS prev_year_sales_revenue, (curr.total_sales_revenue - LAG(curr.total_sales_revenue) OVER(PARTITION BY curr.item_description ORDER BY curr.year)) / LAG(curr.total_sales_revenue) OVER(PARTITION BY curr.item_description ORDER BY curr.year) * 100 AS yoy_growth_percentage FROM AnnualSales curr ), total_info AS ( SELECT item_description, year, total_sales_revenue, unique_purchases, prev_year_sales_revenue, yoy_growth_percentage FROM YoYGrowth WHERE year = 2023 AND prev_year_sales_revenue IS NOT NULL -- Exclude rows where there's no previous year data to calculate YoY growth ORDER BY year, total_sales_revenue DESC ) SELECT item_description FROM total_info order by yoy_growth_percentage DESC LIMIT 5",lite,bq218,sales.date; sales.invoice_and_item_number; sales.item_description; sales.sale_dollars,4,48,True,ok,False,bq218 sf_bq219,IOWA_LIQUOR_SALES,snowflake,"In the Iowa Liquor Sales dataset, starting from January 1, 2022 through the last fully completed month, which two liquor categories, each contributing an average of at least 1% to the monthly sales volume over at least 24 months of available data, have the lowest Pearson correlation coefficient when comparing their monthly percentages of total liquor sales across those months, and what are their names?","WITH MonthlyCategorySales AS ( SELECT DATE_TRUNC('month', ""date"") AS sales_month, ""category_name"", SUM(""volume_sold_liters"") AS category_volume FROM ""IOWA_LIQUOR_SALES"".""IOWA_LIQUOR_SALES"".""SALES"" WHERE ""date"" >= '2022-01-01' AND ""date"" < '2024-09-01' AND ""category_name"" IS NOT NULL GROUP BY 1, 2 ), TotalMonthlySales AS ( SELECT sales_month, SUM(category_volume) AS total_volume FROM MonthlyCategorySales GROUP BY 1 ), MonthlyCategoryPercentage AS ( SELECT mcs.sales_month, mcs.""category_name"", (mcs.category_volume / tms.total_volume) AS percentage_of_volume FROM MonthlyCategorySales mcs JOIN TotalMonthlySales tms ON mcs.sales_month = tms.sales_month ), EligibleCategories AS ( SELECT ""category_name"" FROM MonthlyCategoryPercentage GROUP BY ""category_name"" HAVING COUNT(DISTINCT sales_month) >= 24 AND AVG(percentage_of_volume) >= 0.01 ) SELECT t1.""category_name"" AS category1, t2.""category_name"" AS category2 FROM MonthlyCategoryPercentage AS t1 JOIN MonthlyCategoryPercentage AS t2 ON t1.sales_month = t2.sales_month AND t1.""category_name"" < t2.""category_name"" WHERE t1.""category_name"" IN (SELECT ""category_name"" FROM EligibleCategories) AND t2.""category_name"" IN (SELECT ""category_name"" FROM EligibleCategories) GROUP BY 1, 2 ORDER BY CORR(t1.percentage_of_volume, t2.percentage_of_volume) LIMIT 1;",snow,sf_bq219,sales.category_name; sales.date; sales.volume_sold_liters,3,48,True,ok,False,sf_bq219 sf_bq221,PATENTS,snowflake,"Identify the CPC technology areas with the highest exponential moving average of patent filings each year (with a smoothing factor of 0.2), considering only the first CPC code for each patent that has a valid filing date and a non-empty application number, and report the full CPC title along with the best year associated with the highest exponential moving average for each CPC group at level 5.","WITH RECURSIVE base AS ( SELECT p.""application_number"", FLOOR(p.""filing_date""/10000) AS ""filing_year"", f.""VALUE"":""code""::string AS ""cpc_code"", f.""INDEX"" AS ""idx"", ROW_NUMBER() OVER (PARTITION BY p.""application_number"" ORDER BY f.""INDEX"") AS ""rn"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p, LATERAL FLATTEN(input => p.""cpc"") f WHERE p.""application_number"" IS NOT NULL AND p.""application_number"" != '' AND p.""filing_date"" IS NOT NULL AND p.""filing_date"" > 0 AND f.""VALUE"":""first""::boolean = true ), pub_first AS ( SELECT ""application_number"", ""filing_year"", ""cpc_code"" FROM base WHERE ""rn"" = 1 ), map_group AS ( SELECT pf.""application_number"", pf.""filing_year"", anc.""symbol"" AS ""group_symbol"", anc.""titleFull"" AS ""group_title"" FROM pub_first pf JOIN ""PATENTS"".""PATENTS"".""CPC_DEFINITION"" cd ON cd.""symbol"" = pf.""cpc_code"" , LATERAL FLATTEN(input => ARRAY_CAT(ARRAY_CONSTRUCT(cd.""symbol""), cd.""parents"")) par JOIN ""PATENTS"".""PATENTS"".""CPC_DEFINITION"" anc ON anc.""symbol"" = par.""VALUE""::string AND anc.""level"" = 5 ), yearly_counts AS ( SELECT ""group_symbol"", ""group_title"", ""filing_year"" AS ""year"", COUNT(DISTINCT ""application_number"") AS ""filings"" FROM map_group GROUP BY 1,2,3 ), group_years AS ( SELECT yc.""group_symbol"", yc.""group_title"", MIN(yc.""year"") AS ""min_year"", MAX(yc.""year"") AS ""max_year"" FROM yearly_counts yc GROUP BY 1,2 ), series AS ( SELECT gy.""group_symbol"", gy.""group_title"", v.""VALUE""::int AS ""year"" FROM group_years gy, LATERAL FLATTEN(input => ARRAY_GENERATE_RANGE(gy.""min_year"", gy.""max_year"" + 1)) v ), series_counts AS ( SELECT s.""group_symbol"", s.""group_title"", s.""year"", COALESCE(yc.""filings"", 0) AS ""filings"" FROM series s LEFT JOIN yearly_counts yc ON yc.""group_symbol"" = s.""group_symbol"" AND yc.""year"" = s.""year"" ), ordered AS ( SELECT ""group_symbol"", ""group_title"", ""year"", ""filings"", ROW_NUMBER() OVER (PARTITION BY ""group_symbol"" ORDER BY ""year"") AS ""ord"" FROM series_counts ), r AS ( SELECT o.""group_symbol"", o.""group_title"", o.""year"", o.""filings"", o.""filings""::float AS ""ema"", o.""ord"" FROM ordered o WHERE o.""ord"" = 1 UNION ALL SELECT o.""group_symbol"", o.""group_title"", o.""year"", o.""filings"", 0.2 * o.""filings"" + 0.8 * r.""ema"" AS ""ema"", o.""ord"" FROM ordered o JOIN r ON o.""group_symbol"" = r.""group_symbol"" AND o.""ord"" = r.""ord"" + 1 ), best_year AS ( SELECT ""group_symbol"", ""group_title"", ""year"" AS ""best_year"", ""ema"" AS ""max_ema"", ROW_NUMBER() OVER (PARTITION BY ""group_symbol"" ORDER BY ""ema"" DESC, ""year"" ASC) AS ""rn"" FROM r ) SELECT ""group_symbol"", ""group_title"", ""best_year"", ""max_ema"" FROM best_year WHERE ""rn"" = 1 ORDER BY ""max_ema"" DESC, ""group_symbol"" ASC;",snow,sf_bq221,cpc_definition.level; cpc_definition.parents; cpc_definition.symbol; cpc_definition.titlefull; publications.application_number; publications.cpc; publications.filing_date,7,79,True,ok,False,sf_bq221 sf_bq222,PATENTS,snowflake,"Find the CPC technology areas in Germany that had the highest exponential moving average (smoothing factor 0.1) of patent filings per year, specifically for patents granted in December 2016. For each CPC group at level 4, show the full title, CPC group, and the year with the highest exponential moving average of patent filings.","WITH december_2016_grants AS ( SELECT DISTINCT SUBSTRING(f.value:""code""::STRING, 1, 4) AS cpc_level4 FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p, LATERAL FLATTEN(input => p.""cpc"") f WHERE p.""country_code"" = 'DE' AND p.""grant_date"" >= 20161201 AND p.""grant_date"" <= 20161231 ), all_german_patents AS ( SELECT ""publication_number"", ""filing_date"", FLOOR(""filing_date"" / 10000) AS filing_year, f.value:""code""::STRING AS cpc_code, SUBSTRING(cpc_code, 1, 4) AS cpc_level4 FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" p, LATERAL FLATTEN(input => p.""cpc"") f WHERE p.""country_code"" = 'DE' AND p.""filing_date"" IS NOT NULL AND p.""filing_date"" > 0 AND cpc_level4 IN (SELECT cpc_level4 FROM december_2016_grants) ), yearly_counts AS ( SELECT cpc_level4, filing_year, COUNT(DISTINCT ""publication_number"") AS patent_count FROM all_german_patents WHERE filing_year > 0 GROUP BY cpc_level4, filing_year ), ordered_counts AS ( SELECT cpc_level4, filing_year, patent_count, ROW_NUMBER() OVER (PARTITION BY cpc_level4 ORDER BY filing_year) AS year_rank FROM yearly_counts ), ema_calculated AS ( SELECT cpc_level4, filing_year, patent_count, patent_count AS ema, year_rank FROM ordered_counts WHERE year_rank = 1 UNION ALL SELECT oc.cpc_level4, oc.filing_year, oc.patent_count, ROUND(0.1 * oc.patent_count + 0.9 * ec.ema, 2) AS ema, oc.year_rank FROM ordered_counts oc JOIN ema_calculated ec ON oc.cpc_level4 = ec.cpc_level4 AND oc.year_rank = ec.year_rank + 1 ), max_ema_per_cpc AS ( SELECT cpc_level4, filing_year, ema, ROW_NUMBER() OVER (PARTITION BY cpc_level4 ORDER BY ema DESC, filing_year DESC) as ema_rank FROM ema_calculated ) SELECT m.cpc_level4 AS cpc_group, cd.""titleFull"" AS full_title, m.filing_year AS year, m.ema AS highest_exponential_moving_average FROM max_ema_per_cpc m LEFT JOIN ""PATENTS"".""PATENTS"".""CPC_DEFINITION"" cd ON m.cpc_level4 = cd.""symbol"" WHERE m.ema_rank = 1 ORDER BY m.ema DESC",snow,sf_bq222,cpc_definition.symbol; cpc_definition.titlefull; publications.country_code; publications.cpc; publications.filing_date; publications.grant_date; publications.publication_number,7,79,True,ok,False,sf_bq222 sf_bq223,PATENTS,snowflake,"Which assignees, excluding DENSO CORP itself, have cited patents assigned to DENSO CORP, and what are the titles of the primary CPC subclasses associated with these citations? Provide the name of each citing assignee (excluding DENSO CORP), the full title of the primary CPC subclass (based on the first CPC code), and the count of citations grouped by the citing assignee and the CPC subclass title. Ensure that only citations of patents with valid filing dates are considered, and focus on the first CPC code for each citing patent. The results should specifically exclude DENSO CORP as a citing assignee.","/* Main Question: Identify non-DENSO assignees that have cited patents assigned to DENSO CORP (with valid filing dates) and list the CPC subclass titles (from the first CPC code) together with the count of such citing patents. High-level approach 1. ""denso_pubs"" – all publications whose assignee list contains any form of “DENSO” *and* have a non-NULL filing date. 2. ""citing_pubs"" – all publications that cite at least one patent in ""denso_pubs"" and themselves have a non-NULL filing date. 3. ""citing_infos"" – for every publication in ""citing_pubs"": • flatten assignees and keep only those **not** containing “denso”; • take the first CPC code (cpc.value:first = TRUE) and reduce it to its 4-character subclass symbol. Each row now represents (citing_pub , clean_assignee_name , cpc_subclass_symbol). 4. Join to PATENTS.PATENTS.CPC_DEFINITION to obtain the full subclass title and aggregate. We count DISTINCT citing publications to avoid double-counting the same patent when it cites multiple DENSO patents. */ WITH ""denso_pubs"" AS ( /* Patents assigned to DENSO (any variant in the name) with a valid filing date */ SELECT DISTINCT ""p"".""publication_number"" AS ""denso_pub"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" ""p"", LATERAL FLATTEN(input => ""p"".""assignee_harmonized"") ""ah"" WHERE ""p"".""filing_date"" IS NOT NULL AND UPPER(""ah"".value:""name""::string) LIKE '%DENSO%' ), ""citing_pubs"" AS ( /* Publications that cite any of the DENSO patents and also have a valid filing date */ SELECT DISTINCT ""cp"".""publication_number"" AS ""citing_pub"" FROM ""PATENTS"".""PATENTS"".""PUBLICATIONS"" ""cp"", LATERAL FLATTEN(input => ""cp"".""citation"") ""cite"" JOIN ""denso_pubs"" ""d"" ON ""cite"".value:""publication_number""::string = ""d"".""denso_pub"" WHERE ""cp"".""filing_date"" IS NOT NULL ), ""citing_infos"" AS ( /* Extract non-DENSO assignee name and first CPC subclass for each citing publication */ SELECT DISTINCT ""cp"".""citing_pub"", TRIM(LOWER(""ass"".value:""name""::string)) AS ""assignee_name"", SUBSTR(""cpc"".value:""code""::string , 1 , 4) AS ""cpc_subclass_symbol"" FROM ""citing_pubs"" ""cp"" JOIN ""PATENTS"".""PATENTS"".""PUBLICATIONS"" ""pub"" ON ""pub"".""publication_number"" = ""cp"".""citing_pub"" , LATERAL FLATTEN(input => ""pub"".""assignee_harmonized"") ""ass"" , LATERAL FLATTEN(input => ""pub"".""cpc"") ""cpc"" WHERE ""ass"".value:""name"" IS NOT NULL AND LOWER(""ass"".value:""name""::string) NOT LIKE '%denso%' AND ""cpc"".value:""first""::boolean = TRUE ) /* Final aggregation: count distinct citing publications per (assignee , CPC subclass title) */ SELECT ""ci"".""assignee_name"" AS ""citing_assignee"", ""cd"".""titleFull"" AS ""cpc_subclass_title"", COUNT(DISTINCT ""ci"".""citing_pub"") AS ""citation_count"" FROM ""citing_infos"" ""ci"" JOIN ""PATENTS"".""PATENTS"".""CPC_DEFINITION"" ""cd"" ON ""cd"".""symbol"" = ""ci"".""cpc_subclass_symbol"" GROUP BY ""ci"".""assignee_name"", ""cd"".""titleFull"" ORDER BY ""citation_count"" DESC, ""citing_assignee"", ""cpc_subclass_title"";",snow,sf_bq223,cpc_definition.symbol; cpc_definition.titlefull; publications.assignee_harmonized; publications.citation; publications.cpc; publications.filing_date; publications.publication_number,7,79,True,fix,False,sf_bq223 sf_bq224,GITHUB_REPOS_DATE,snowflake,"Which repository with an approved license in `licenses.md` had the highest combined total of forks, issues, and watches in April 2022?","WITH approved_repos AS ( SELECT DISTINCT T1.""repo_name"" FROM GITHUB_REPOS_DATE.GITHUB_REPOS.LICENSES T1 JOIN GITHUB_REPOS_DATE.GITHUB_REPOS.LICENSES T2 ON LOWER(T1.""license"") = LOWER(T2.""license"") ), events_agg AS ( SELECT TRY_PARSE_JSON(E.""repo""):""name""::STRING AS repo_name, SUM(CASE WHEN E.""type"" = 'ForkEvent' THEN 1 ELSE 0 END) AS fork_events, SUM(CASE WHEN E.""type"" = 'IssuesEvent' THEN 1 ELSE 0 END) AS issues_events, SUM(CASE WHEN E.""type"" = 'WatchEvent' THEN 1 ELSE 0 END) AS watch_events FROM GITHUB_REPOS_DATE.MONTH._202204 E WHERE TO_TIMESTAMP(E.""created_at"" / 1000000) >= '2022-04-01' AND TO_TIMESTAMP(E.""created_at"" / 1000000) < '2022-05-01' AND E.""type"" IN ('ForkEvent','IssuesEvent','WatchEvent') GROUP BY TRY_PARSE_JSON(E.""repo""):""name""::STRING ), totals AS ( SELECT repo_name, fork_events + issues_events + watch_events AS total_events FROM events_agg ) SELECT T.repo_name FROM totals T JOIN approved_repos A ON T.repo_name = A.""repo_name"" ORDER BY T.total_events DESC LIMIT 1;",snow,sf_bq224,_20_*.created_at; _20_*.repo; _20_*.type; licenses.license; licenses.repo_name,5,43,True,ok,False,sf_bq224 sf_bq227,LONDON,bigquery,"Could you provide the annual percentage shares, rounded to two decimal places, of the top 5 minor crime categories from 2008 in London's total crimes, with each year displayed in one row?","WITH top5_categories AS ( SELECT minor_category FROM `bigquery-public-data.london_crime.crime_by_lsoa` WHERE year = 2008 GROUP BY minor_category ORDER BY SUM(value) DESC LIMIT 5 ), total_crimes_per_year AS ( SELECT year, SUM(value) AS total_crimes_year FROM `bigquery-public-data.london_crime.crime_by_lsoa` GROUP BY year ), top5_crimes_per_year AS ( SELECT year, minor_category, SUM(value) AS total_crimes_category_year FROM `bigquery-public-data.london_crime.crime_by_lsoa` WHERE minor_category IN (SELECT minor_category FROM top5_categories) GROUP BY year, minor_category ) SELECT t.year, ROUND(SUM(CASE WHEN t.minor_category = (SELECT minor_category FROM top5_categories LIMIT 1 OFFSET 0) THEN t.total_crimes_category_year ELSE 0 END) / y.total_crimes_year * 100, 2) AS `Category 1`, ROUND(SUM(CASE WHEN t.minor_category = (SELECT minor_category FROM top5_categories LIMIT 1 OFFSET 1) THEN t.total_crimes_category_year ELSE 0 END) / y.total_crimes_year * 100, 2) AS `Category 2`, ROUND(SUM(CASE WHEN t.minor_category = (SELECT minor_category FROM top5_categories LIMIT 1 OFFSET 2) THEN t.total_crimes_category_year ELSE 0 END) / y.total_crimes_year * 100, 2) AS `Category 3`, ROUND(SUM(CASE WHEN t.minor_category = (SELECT minor_category FROM top5_categories LIMIT 1 OFFSET 3) THEN t.total_crimes_category_year ELSE 0 END) / y.total_crimes_year * 100, 2) AS `Category 4`, ROUND(SUM(CASE WHEN t.minor_category = (SELECT minor_category FROM top5_categories LIMIT 1 OFFSET 4) THEN t.total_crimes_category_year ELSE 0 END) / y.total_crimes_year * 100, 2) AS `Category 5` FROM top5_crimes_per_year t JOIN total_crimes_per_year y ON t.year = y.year GROUP BY t.year, y.total_crimes_year ORDER BY t.year; ",lite,bq227,crime_by_lsoa.minor_category; crime_by_lsoa.value; crime_by_lsoa.year,3,39,True,ok,False,bq227 sf_bq228,LONDON,bigquery,"Please provide a list of the top three major crime categories in the borough of Barking and Dagenham, along with the number of incidents in each category.","WITH ranked_crimes AS ( SELECT borough, major_category, RANK() OVER(PARTITION BY borough ORDER BY SUM(value) DESC) AS rank_per_borough, SUM(value) AS no_of_incidents FROM `bigquery-public-data.london_crime.crime_by_lsoa` GROUP BY borough, major_category ) SELECT borough, major_category, rank_per_borough, no_of_incidents FROM ranked_crimes WHERE rank_per_borough <= 3 AND borough = 'Barking and Dagenham' ORDER BY borough, rank_per_borough;",lite,bq228,crime_by_lsoa.borough; crime_by_lsoa.major_category; crime_by_lsoa.value,3,39,True,ok,False,bq228 sf_bq232,LONDON,bigquery,Could you provide the total number of 'Other Theft' incidents within the 'Theft and Handling' category for each year in the Westminster borough?,"WITH borough_data AS ( SELECT year, month, borough, major_category, minor_category, SUM(value) AS total, CASE WHEN major_category = 'Theft and Handling' THEN 'Theft and Handling' ELSE 'Other' END AS major_division, CASE WHEN minor_category = 'Other Theft' THEN minor_category ELSE 'Other' END AS minor_division, FROM bigquery-public-data.london_crime.crime_by_lsoa GROUP BY 1,2,3,4,5 ORDER BY 1,2 ) SELECT year, SUM(total) AS year_total FROM borough_data WHERE borough = 'Westminster' AND major_division != 'Other' AND minor_division != 'Other' GROUP BY year, major_division, minor_division ORDER BY year;",lite,bq232,crime_by_lsoa.borough; crime_by_lsoa.major_category; crime_by_lsoa.minor_category; crime_by_lsoa.month; crime_by_lsoa.value; crime_by_lsoa.year,6,39,True,ok,False,bq232 sf_bq233,GITHUB_REPOS,snowflake,"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?","WITH python_files AS ( SELECT sf.""path"", sc.""content"", 'Python' as language FROM GITHUB_REPOS.GITHUB_REPOS.SAMPLE_FILES sf JOIN GITHUB_REPOS.GITHUB_REPOS.SAMPLE_CONTENTS sc ON sf.""id"" = sc.""id"" WHERE sc.""binary"" = FALSE AND sf.""path"" ILIKE '%.py' ), python_import_lines AS ( SELECT language, ""path"", TRIM(line.value) as line_content FROM python_files, LATERAL SPLIT_TO_TABLE(""content"", '\n') line WHERE TRIM(line.value) LIKE 'import %' OR TRIM(line.value) LIKE 'from %import%' ), parsed_python_imports AS ( SELECT language, CASE -- Handle ""import module"" statements - extract first module name WHEN line_content LIKE 'import %' AND line_content NOT LIKE 'from %' THEN TRIM(SPLIT_PART(SPLIT_PART(line_content, 'import ', 2), ',', 1)) -- Handle ""from module import ..."" statements - extract the main module WHEN line_content LIKE 'from %import%' THEN TRIM(SPLIT_PART(SPLIT_PART(line_content, 'from ', 2), ' import', 1)) ELSE NULL END as full_module_name FROM python_import_lines WHERE line_content IS NOT NULL AND line_content != '' ), python_base_modules AS ( SELECT language, -- Extract the base module name (first part before dot) SPLIT_PART(full_module_name, '.', 1) as module_name FROM parsed_python_imports WHERE full_module_name IS NOT NULL AND full_module_name != '' ), python_results AS ( SELECT language, module_name, COUNT(*) as occurrence_count FROM python_base_modules WHERE module_name IS NOT NULL AND module_name != '' GROUP BY language, module_name ), r_files AS ( SELECT ""sample_path"" as r_path, ""content"", 'R' as language FROM GITHUB_REPOS.GITHUB_REPOS.SAMPLE_CONTENTS WHERE ""binary"" = FALSE AND (""sample_path"" ILIKE '%.r' OR ""sample_path"" ILIKE '%.R' OR ""sample_path"" ILIKE '%.Rmd') ), r_import_lines AS ( SELECT language, r_path, TRIM(line.value) as line_content FROM r_files, LATERAL SPLIT_TO_TABLE(""content"", '\n') line WHERE TRIM(line.value) LIKE 'library(%' OR TRIM(line.value) LIKE 'require(%' ), parsed_r_imports AS ( SELECT language, CASE -- Handle library() statements WHEN line_content LIKE 'library(%' THEN TRIM(REPLACE(REPLACE(SPLIT_PART(SPLIT_PART(line_content, 'library(', 2), ')', 1), '""', ''), '\\', '')) -- Handle require() statements WHEN line_content LIKE 'require(%' THEN TRIM(REPLACE(REPLACE(SPLIT_PART(SPLIT_PART(line_content, 'require(', 2), ')', 1), '""', ''), '\\', '')) ELSE NULL END as library_name FROM r_import_lines WHERE line_content IS NOT NULL AND line_content != '' ), r_results AS ( SELECT language, library_name as module_name, COUNT(*) as occurrence_count FROM parsed_r_imports WHERE library_name IS NOT NULL AND library_name != '' GROUP BY language, library_name ), combined_results AS ( SELECT language, module_name, occurrence_count FROM python_results UNION ALL SELECT language, module_name, occurrence_count FROM r_results ) SELECT language, module_name, occurrence_count FROM combined_results ORDER BY language, occurrence_count DESC, module_name",snow,sf_bq233,sample_contents.binary; sample_contents.content; sample_contents.id; sample_contents.sample_path; sample_files.id; sample_files.path,6,34,True,ok,False,sf_bq233 sf_bq234,CMS_DATA,bigquery,What is the most prescribed medication in each state in 2014?,"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;",lite,bq234,part_d_prescriber_2014.generic_name; part_d_prescriber_2014.nppes_provider_state; part_d_prescriber_2014.total_claim_count; part_d_prescriber_2014.total_day_supply; part_d_prescriber_2014.total_drug_cost,5,694,True,fix,True,bq234 sf_bq235,CMS_DATA,bigquery,Can you tell me which healthcare provider incurs the highest combined average costs for both outpatient and inpatient services in 2014?,"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 );",lite,bq235,inpatient_charges_*.average_medicare_payments; inpatient_charges_*.provider_city; inpatient_charges_*.provider_id; inpatient_charges_*.provider_name; inpatient_charges_*.provider_state; inpatient_charges_*.total_discharges; outpatient_charges_*.average_total_payments; outpatient_charges_*.outpatient_services; outpatient_charges_*.provider_city; outpatient_charges_*.provider_id; outpatient_charges_*.provider_name; outpatient_charges_*.provider_state,12,694,True,fix,True,bq235 sf_bq236,NOAA_DATA_PLUS,snowflake,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.,"WITH threshold AS ( SELECT DATEADD(year, -10, CURRENT_DATE()) AS min_event_date ), hail_events AS ( SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000) AS event_ts, ""event_latitude"" AS event_lat, ""event_longitude"" AS event_lon FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2014"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2015"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2016"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2017"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2018"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2019"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2020"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2021"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2022"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2023"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL UNION ALL SELECT TO_TIMESTAMP_NTZ(""event_begin_time"" / 1000000), ""event_latitude"", ""event_longitude"" FROM ""NOAA_DATA_PLUS"".""NOAA_HISTORIC_SEVERE_STORMS"".""STORMS_2024"" WHERE UPPER(""event_type"") = 'HAIL' AND ""event_latitude"" IS NOT NULL AND ""event_longitude"" IS NOT NULL ), recent_hail AS ( SELECT e.event_ts, e.event_lat, e.event_lon FROM hail_events e JOIN threshold t ON e.event_ts >= t.min_event_date ), hail_with_zip AS ( SELECT z.""zip_code"", COUNT(*) AS hail_event_count FROM recent_hail r JOIN ""NOAA_DATA_PLUS"".""GEO_US_BOUNDARIES"".""ZIP_CODES"" z ON ST_WITHIN(ST_POINT(r.event_lon, r.event_lat), TO_GEOGRAPHY(z.""zip_code_geom"")) GROUP BY z.""zip_code"" ) SELECT ""zip_code"", hail_event_count FROM hail_with_zip ORDER BY hail_event_count DESC, ""zip_code"" FETCH FIRST 5 ROWS ONLY;",snow,sf_bq236,storms_*.event_begin_time; storms_*.event_latitude; storms_*.event_longitude; storms_*.event_type; zip_codes.zip_code; zip_codes.zip_code_geom,6,855,True,ok,False,sf_bq236 sf_bq246,PATENTSVIEW,snowflake,"Retrieve U.S. patents with the number of forward citations within the first 3 years after the patent application date (i.e., patents citing the current patent within 3 years). Only include patents with both backward citations within 1 year before the application date and forward citations within 1 year after the application date. The query should focus on specific CPC categories, sort results by backward citations in descending order, and return the patent with the most backward citations, limiting to one result.","WITH ""cte_app"" AS ( SELECT a.""patent_id"", MIN(TRY_TO_DATE(a.""date"")) AS ""app_date"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""APPLICATION"" a WHERE TRY_TO_DATE(a.""date"") IS NOT NULL GROUP BY a.""patent_id"" ), ""base"" AS ( SELECT DISTINCT p.""id"" AS ""patent_id"", p.""number"" AS ""patent_number"", ca.""app_date"" AS ""application_date"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""PATENT"" p JOIN ""cte_app"" ca ON ca.""patent_id"" = p.""id"" JOIN ""PATENTSVIEW"".""PATENTSVIEW"".""CPC_CURRENT"" cpc ON cpc.""patent_id"" = p.""id"" WHERE p.""country"" = 'US' AND cpc.""category"" = 'inventional' ), ""back_1y"" AS ( SELECT b.""patent_id"", COUNT(DISTINCT b.""citation_id"") AS ""back_1y_count"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""USPATENTCITATION"" b JOIN ""base"" ba ON ba.""patent_id"" = b.""patent_id"" JOIN ""cte_app"" app_cited ON app_cited.""patent_id"" = b.""citation_id"" WHERE app_cited.""app_date"" >= DATEADD(year, -1, ba.""application_date"") AND app_cited.""app_date"" < ba.""application_date"" GROUP BY b.""patent_id"" ), ""fwd_1y"" AS ( SELECT f.""citation_id"" AS ""patent_id"", COUNT(DISTINCT f.""patent_id"") AS ""fwd_1y_count"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""USPATENTCITATION"" f JOIN ""base"" ba ON ba.""patent_id"" = f.""citation_id"" JOIN ""cte_app"" app_citing ON app_citing.""patent_id"" = f.""patent_id"" WHERE app_citing.""app_date"" >= ba.""application_date"" AND app_citing.""app_date"" <= DATEADD(year, 1, ba.""application_date"") GROUP BY f.""citation_id"" ), ""fwd_3y"" AS ( SELECT f.""citation_id"" AS ""patent_id"", COUNT(DISTINCT f.""patent_id"") AS ""fwd_3y_count"" FROM ""PATENTSVIEW"".""PATENTSVIEW"".""USPATENTCITATION"" f JOIN ""base"" ba ON ba.""patent_id"" = f.""citation_id"" JOIN ""cte_app"" app_citing ON app_citing.""patent_id"" = f.""patent_id"" WHERE app_citing.""app_date"" >= ba.""application_date"" AND app_citing.""app_date"" <= DATEADD(year, 3, ba.""application_date"") GROUP BY f.""citation_id"" ) SELECT b.""patent_id"", b.""patent_number"", b.""application_date"", COALESCE(bk.""back_1y_count"", 0) AS ""backward_citations_within_1y_before_app"", COALESCE(f1.""fwd_1y_count"", 0) AS ""forward_citations_within_1y_after_app"", COALESCE(f3.""fwd_3y_count"", 0) AS ""forward_citations_within_3y_after_app"" FROM ""base"" b LEFT JOIN ""back_1y"" bk ON bk.""patent_id"" = b.""patent_id"" LEFT JOIN ""fwd_1y"" f1 ON f1.""patent_id"" = b.""patent_id"" LEFT JOIN ""fwd_3y"" f3 ON f3.""patent_id"" = b.""patent_id"" WHERE COALESCE(bk.""back_1y_count"", 0) > 0 AND COALESCE(f1.""fwd_1y_count"", 0) > 0 ORDER BY bk.""back_1y_count"" DESC LIMIT 1;",snow,sf_bq246,application.date; application.patent_id; cpc_current.category; cpc_current.patent_id; patent.country; patent.id; patent.number; uspatentcitation.citation_id; uspatentcitation.patent_id,9,295,True,ok,False,sf_bq246 sf_bq248,GITHUB_REPOS,snowflake,"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)""?","-- Answer: proportion of README.md files (in non-Python repositories) whose contents include ""Copyright (c)"" -- 1) Filter SAMPLE_CONTENTS to files whose path contains ""readme.md"" (case-insensitive). -- 2) Exclude any repository that uses a language whose name contains the substring ""python"" (case-insensitive). -- To detect such repositories, FLATTEN the VARIANT array ""language"" and look at the ""name"" field. -- 3) Compute the proportion = (# files with the phrase) / (total # README.md files) as a floating value. SELECT /* numerator: files whose content contains the phrase */ COUNT_IF(LOWER(sc.""content"") LIKE '%copyright (c)%')::DOUBLE / /* denominator: total README.md files in non-Python repos */ NULLIF(COUNT(*), 0) AS ""proportion"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""SAMPLE_CONTENTS"" sc WHERE LOWER(sc.""sample_path"") LIKE '%readme.md%' AND NOT EXISTS ( SELECT 1 FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""LANGUAGES"" l, LATERAL FLATTEN(input => l.""language"") f WHERE l.""repo_name"" = sc.""sample_repo_name"" AND LOWER(f.value:""name""::string) LIKE '%python%' );",snow,sf_bq248,languages.language; languages.repo_name; sample_contents.content; sample_contents.sample_path; sample_contents.sample_repo_name,5,34,True,ok,False,sf_bq248 sf_bq250,GEO_OPENSTREETMAP_WORLDPOP,snowflake,"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?","WITH singapore_hospitals AS (SELECT pl.""osm_id"", CASE WHEN pl.""gdal_type"" = 'points' THEN ST_GEOGFROMWKB(pl.""geometry"") ELSE ST_CENTROID(ST_GEOGFROMWKB(pl.""geometry"")) END as hospital_point FROM GEO_OPENSTREETMAP_WORLDPOP.GEO_OPENSTREETMAP.PLANET_LAYERS pl WHERE pl.""layer_class"" = 'poi_health' AND pl.""layer_name"" = 'hospital' AND pl.""geometry"" IS NOT NULL AND ST_X(CASE WHEN pl.""gdal_type"" = 'points' THEN ST_GEOGFROMWKB(pl.""geometry"") ELSE ST_CENTROID(ST_GEOGFROMWKB(pl.""geometry"")) END) BETWEEN 103.64 AND 103.99 AND ST_Y(CASE WHEN pl.""gdal_type"" = 'points' THEN ST_GEOGFROMWKB(pl.""geometry"") ELSE ST_CENTROID(ST_GEOGFROMWKB(pl.""geometry"")) END) BETWEEN 1.27 AND 1.45), singapore_population_grids AS (SELECT ""geo_id"", ""population"", ""latitude_centroid"", ""longitude_centroid"", ST_GEOGFROMWKB(""geog"") as grid_point FROM GEO_OPENSTREETMAP_WORLDPOP.WORLDPOP.POPULATION_GRID_1KM WHERE ""alpha_3_code"" = 'SGP' AND ""last_updated"" = '2020-01-01' AND ""population"" > 0), grid_distances AS (SELECT spg.""geo_id"", spg.""population"", MIN(ST_DISTANCE(spg.grid_point, sh.hospital_point)) as min_distance_to_hospital FROM singapore_population_grids spg CROSS JOIN singapore_hospitals sh GROUP BY spg.""geo_id"", spg.""population""), max_distance AS (SELECT MAX(min_distance_to_hospital) as maximum_distance FROM grid_distances), farthest_grid AS (SELECT gd.""geo_id"", gd.""population"", gd.min_distance_to_hospital FROM grid_distances gd, max_distance md WHERE gd.min_distance_to_hospital = md.maximum_distance) SELECT SUM(""population"") as total_population FROM farthest_grid",snow,sf_bq250,planet_layers.gdal_type; planet_layers.geometry; planet_layers.layer_class; planet_layers.layer_name; planet_layers.osm_id; population_grid_1km.alpha_3_code; population_grid_1km.geo_id; population_grid_1km.geog; population_grid_1km.last_updated; population_grid_1km.latitude_centroid; population_grid_1km.longitude_centroid; population_grid_1km.population,12,94,True,ok,False,sf_bq250 sf_bq252,GITHUB_REPOS,snowflake,"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?"," SELECT f.""repo_name"" AS repository_name FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""SAMPLE_CONTENTS"" c JOIN ""GITHUB_REPOS"".""GITHUB_REPOS"".""SAMPLE_FILES"" f ON c.""id"" = f.""id"" WHERE c.""sample_path"" ILIKE '%.swift' AND c.""binary"" = FALSE ORDER BY c.""copies"" DESC NULLS LAST LIMIT 1; ",snow,sf_bq252,sample_contents.binary; sample_contents.copies; sample_contents.id; sample_contents.sample_path; sample_files.id; sample_files.repo_name,6,34,True,ok,False,sf_bq252 sf_bq254,GEO_OPENSTREETMAP,snowflake,"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?","/* Assumptions & reasoning (see guidelines comments requirement): 1. The multipolygon representing Wikidata Q191 (Estonia) is stored in GEO_OPENSTREETMAP.PLANET_FEATURES with feature_type = 'multipolygons'. We fetch its (single) geometry as our target area. 2. “Same geographic area” is interpreted as geometries that intersect the Estonia multipolygon – ST_INTERSECTS is therefore used. 3. Candidates are all multipolygons from the same table that (a) have a non-NULL geometry, (b) do NOT carry any tag with key = 'wikidata'. 4.  all_tags is a JSON array; to avoid expensive LATERAL FLATTEN scans on the full table we first pre-filter with NOT ILIKE '%""wikidata""%'. The small subset that passes the spatial test is then flattened once to extract the *name* tag. 5. Point features are taken from PLANET_FEATURES_POINTS. Only points with a non-NULL geometry are considered. ST_CONTAINS(g_poly , g_pt) gives the per-polygon contained-point count. 6. We order by descending point count and return the top two with their names (may be NULL if no name tag exists). */ WITH target_estonia AS ( /* geometry of the multipolygon tagged wikidata = Q191 (Estonia) */ SELECT TO_GEOGRAPHY(pf.""geometry"") AS geom FROM ""GEO_OPENSTREETMAP"".""GEO_OPENSTREETMAP"".""PLANET_FEATURES"" pf ,LATERAL FLATTEN(input => pf.""all_tags"") tag WHERE pf.""feature_type"" = 'multipolygons' AND tag.value:""key""::string = 'wikidata' AND tag.value:""value""::string = 'Q191' LIMIT 1 ), candidate_raw AS ( /* multipolygons without a wikidata tag, having geometry, intersecting Estonia */ SELECT COALESCE(pf.""osm_way_id"", pf.""osm_id"") AS id, pf.""geometry"" AS geom_bin, pf.""all_tags"" AS tags FROM ""GEO_OPENSTREETMAP"".""GEO_OPENSTREETMAP"".""PLANET_FEATURES"" pf CROSS JOIN target_estonia t WHERE pf.""feature_type"" = 'multipolygons' AND pf.""geometry"" IS NOT NULL AND LOWER(TO_VARCHAR(pf.""all_tags"")) NOT ILIKE '%""wikidata""%' AND ST_INTERSECTS(TO_GEOGRAPHY(pf.""geometry""), t.geom) ), name_tags AS ( /* extract (optional) name tag for every candidate */ SELECT cr.id, MAX(tag.value:""value""::string) AS name_tag FROM candidate_raw cr, LATERAL FLATTEN(input => cr.tags) tag WHERE tag.value:""key""::string = 'name' GROUP BY cr.id ), geom_candidates AS ( SELECT id, TO_GEOGRAPHY(geom_bin) AS geom FROM candidate_raw ), point_counts AS ( SELECT gc.id AS multipolygon_id, nt.name_tag AS name, COUNT(*) AS point_cnt FROM geom_candidates gc LEFT JOIN name_tags nt ON nt.id = gc.id JOIN ""GEO_OPENSTREETMAP"".""GEO_OPENSTREETMAP"".""PLANET_FEATURES_POINTS"" p ON p.""geometry"" IS NOT NULL AND ST_CONTAINS(gc.geom, TO_GEOGRAPHY(p.""geometry"")) GROUP BY gc.id, nt.name_tag ) SELECT multipolygon_id AS id, name, point_cnt FROM point_counts ORDER BY point_cnt DESC, name LIMIT 2;",snow,sf_bq254,planet_features.all_tags; planet_features.feature_type; planet_features.geometry; planet_features.osm_id; planet_features.osm_way_id; planet_features_points.geometry,6,86,True,ok,False,sf_bq254 sf_bq255,GITHUB_REPOS,snowflake,"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'?","SELECT COUNT(*) AS ""commit_count"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""SAMPLE_COMMITS"" AS ""sc"" INNER JOIN ( SELECT DISTINCT ""l"".""repo_name"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""LANGUAGES"" AS ""l"", LATERAL FLATTEN(INPUT => ""l"".""language"") AS ""lang"" WHERE LOWER(""lang"".""VALUE"":""name""::STRING) = 'shell' ) AS ""shell_repos"" ON ""sc"".""repo_name"" = ""shell_repos"".""repo_name"" INNER JOIN ( SELECT DISTINCT ""repo_name"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""LICENSES"" WHERE LOWER(""license"") = 'apache-2.0' ) AS ""licensed_repos"" ON ""sc"".""repo_name"" = ""licensed_repos"".""repo_name"" WHERE ""sc"".""message"" IS NOT NULL AND LENGTH(""sc"".""message"") > 5 AND LENGTH(""sc"".""message"") < 10000 AND NOT REGEXP_LIKE(LOWER(LTRIM(""sc"".""message"")), '^(merge|update|test)\b');",snow,sf_bq255,languages.language; languages.repo_name; licenses.license; licenses.repo_name; sample_commits.message; sample_commits.repo_name,6,34,True,ok,False,sf_bq255 sf_bq260,THELOOK_ECOMMERCE,snowflake,"From January 1, 2019, to April 30, 2022, how many users are at the youngest age and how many users are at the oldest age for each gender in the e-commerce platform, counting both youngest and oldest users separately for each gender?","WITH FilteredUsers AS ( SELECT ""gender"", ""age"" FROM ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""USERS"" WHERE TO_TIMESTAMP_NTZ(""created_at"" / 1000000) >= '2019-01-01' AND TO_TIMESTAMP_NTZ(""created_at"" / 1000000) < '2022-05-01' ), AgeBounds AS ( SELECT ""gender"", MIN(""age"") AS min_age, MAX(""age"") AS max_age FROM FilteredUsers GROUP BY ""gender"" ) SELECT T1.""gender"", COUNT(CASE WHEN T1.""age"" = T2.min_age THEN 1 END) AS youngest_count, COUNT(CASE WHEN T1.""age"" = T2.max_age THEN 1 END) AS oldest_count FROM FilteredUsers AS T1 JOIN AgeBounds AS T2 ON T1.""gender"" = T2.""gender"" WHERE T1.""age"" = T2.min_age OR T1.""age"" = T2.max_age GROUP BY T1.""gender"";",snow,sf_bq260,users.age; users.created_at; users.gender,3,73,True,ok,False,sf_bq260 sf_bq263,THELOOK_ECOMMERCE,snowflake,"Please create a month-by-month report for the year 2023 that focuses on the 'Sleep & Lounge' category, showing for each month the total sales, total cost, number of complete orders, total profit, and the profit-to-cost ratio, ensuring that the order is marked as 'Complete,' the creation date is between January 1, 2023, and December 31, 2023, and the cost data is accurately associated with the corresponding product through the order items. ","SELECT DATE_TRUNC('month', TO_TIMESTAMP_NTZ(""O"".""created_at"" / 1000000)) AS ""month"", SUM(""OI"".""sale_price"") AS ""total_sales"", SUM(""P"".""cost"") AS ""total_cost"", COUNT(DISTINCT ""O"".""order_id"") AS ""complete_orders"", SUM(""OI"".""sale_price"" - ""P"".""cost"") AS ""total_profit"", CASE WHEN SUM(""P"".""cost"") = 0 THEN NULL ELSE SUM(""OI"".""sale_price"" - ""P"".""cost"") / SUM(""P"".""cost"") END AS ""profit_to_cost_ratio"" FROM ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""ORDER_ITEMS"" AS ""OI"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""ORDERS"" AS ""O"" ON ""OI"".""order_id"" = ""O"".""order_id"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""PRODUCTS"" AS ""P"" ON ""OI"".""product_id"" = ""P"".""id"" WHERE ""O"".""status"" = 'Complete' AND ""P"".""category"" = 'Sleep & Lounge' AND TO_TIMESTAMP_NTZ(""O"".""created_at"" / 1000000) >= '2023-01-01' AND TO_TIMESTAMP_NTZ(""O"".""created_at"" / 1000000) < '2024-01-01' GROUP BY 1 ORDER BY 1;",snow,sf_bq263,order_items.order_id; order_items.product_id; order_items.sale_price; orders.created_at; orders.order_id; orders.status; products.category; products.cost; products.id,9,73,True,ok,False,sf_bq263 sf_bq264,THELOOK_ECOMMERCE,snowflake,"Identify the difference in the number of the oldest and youngest users registered between January 1, 2019, and April 30, 2022, from our e-commerce platform data.","WITH MinMaxAge AS ( SELECT MIN(""age"") AS min_age, MAX(""age"") AS max_age FROM ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""USERS"" WHERE CAST(TO_TIMESTAMP_NTZ(""created_at"" / 1000000) AS DATE) BETWEEN '2019-01-01' AND '2022-04-30' ) SELECT SUM(CASE WHEN T.""age"" = M.max_age THEN 1 ELSE 0 END) - SUM(CASE WHEN T.""age"" = M.min_age THEN 1 ELSE 0 END) FROM ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""USERS"" AS T CROSS JOIN MinMaxAge AS M WHERE CAST(TO_TIMESTAMP_NTZ(T.""created_at"" / 1000000) AS DATE) BETWEEN '2019-01-01' AND '2022-04-30'",snow,sf_bq264,users.age; users.created_at,2,73,True,ok,False,sf_bq264 sf_bq265,THELOOK_ECOMMERCE,snowflake,"Can you list the email addresses of the top 10 users who registered in 2019 and made purchases in 2019, ranking them by their highest average order value, where average order value is calculated by multiplying the number of items in each order by the sale price, summing this total across all orders for each user, and then dividing by the total number of orders?","WITH users_2019 AS ( SELECT ""id"" AS ""user_id"", ""email"" FROM THELOOK_ECOMMERCE.THELOOK_ECOMMERCE.USERS WHERE TO_TIMESTAMP_NTZ(""created_at"" / 1000000.0) >= TO_TIMESTAMP_NTZ('2019-01-01') AND TO_TIMESTAMP_NTZ(""created_at"" / 1000000.0) < TO_TIMESTAMP_NTZ('2020-01-01') ), orders_2019 AS ( SELECT ""order_id"", ""user_id"" FROM THELOOK_ECOMMERCE.THELOOK_ECOMMERCE.ORDERS WHERE TO_TIMESTAMP_NTZ(""created_at"" / 1000000.0) >= TO_TIMESTAMP_NTZ('2019-01-01') AND TO_TIMESTAMP_NTZ(""created_at"" / 1000000.0) < TO_TIMESTAMP_NTZ('2020-01-01') AND ""status"" NOT IN ('Cancelled','Returned') ), order_items_valid AS ( SELECT ""order_id"", ""sale_price"" FROM THELOOK_ECOMMERCE.THELOOK_ECOMMERCE.ORDER_ITEMS WHERE ""status"" NOT IN ('Cancelled','Returned') AND ""sale_price"" IS NOT NULL ), per_order_revenue AS ( SELECT o.""order_id"", o.""user_id"", SUM(oi.""sale_price"") AS ""order_revenue"" FROM orders_2019 o JOIN order_items_valid oi ON o.""order_id"" = oi.""order_id"" GROUP BY o.""order_id"", o.""user_id"" ), per_user AS ( SELECT por.""user_id"", SUM(por.""order_revenue"") AS ""total_revenue"", COUNT(DISTINCT por.""order_id"") AS ""order_count"", SUM(por.""order_revenue"") / NULLIF(COUNT(DISTINCT por.""order_id""), 0) AS ""aov"" FROM per_order_revenue por GROUP BY por.""user_id"" ) SELECT u.""email"" AS ""email"" FROM users_2019 u JOIN per_user p ON u.""user_id"" = p.""user_id"" ORDER BY p.""aov"" DESC NULLS LAST, u.""email"" ASC LIMIT 10;",snow,sf_bq265,order_items.order_id; order_items.sale_price; order_items.status; orders.created_at; orders.order_id; orders.status; orders.user_id; users.created_at; users.email; users.id,10,73,True,fix,True,sf_bq265 sf_bq268,GA360,bigquery,"Identify the longest number of days between the first visit and the last recorded event (either the last visit or the first transaction) for a user, where the last recorded event is associated with a mobile device. The last recorded event could either be the last visit or the first transaction, and you should focus on users whose last recorded event occurred on a mobile device.","WITH visit AS ( SELECT fullvisitorid, MIN(date) AS date_first_visit, MAX(date) AS date_last_visit FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` GROUP BY fullvisitorid), device_visit AS ( SELECT DISTINCT fullvisitorid, date, device.deviceCategory FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`), transactions AS ( SELECT fullvisitorid, MIN(date) AS date_transactions, 1 AS transaction FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` AS ga, UNNEST(ga.hits) AS hits WHERE hits.transaction.transactionId IS NOT NULL GROUP BY fullvisitorid), device_transactions AS ( SELECT DISTINCT fullvisitorid, date, device.deviceCategory FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` AS ga, UNNEST(ga.hits) AS hits WHERE hits.transaction.transactionId IS NOT NULL), visits_transactions AS ( SELECT visit.fullvisitorid, date_first_visit, date_transactions, date_last_visit , device_visit.deviceCategory AS device_last_visit, device_transactions.deviceCategory AS device_transaction, IFNULL(transactions.transaction,0) AS transaction FROM visit LEFT JOIN transactions ON visit.fullvisitorid = transactions.fullvisitorid LEFT JOIN device_visit ON visit.fullvisitorid = device_visit.fullvisitorid AND visit.date_last_visit = device_visit.date LEFT JOIN device_transactions ON visit.fullvisitorid = device_transactions.fullvisitorid AND transactions.date_transactions = device_transactions.date ), mortality_table AS ( SELECT fullvisitorid, date_first_visit, CASE WHEN date_transactions IS NULL THEN date_last_visit ELSE date_transactions END AS date_event, CASE WHEN device_transaction IS NULL THEN device_last_visit ELSE device_transaction END AS device, transaction FROM visits_transactions ) SELECT DATE_DIFF(PARSE_DATE('%Y%m%d',date_event), PARSE_DATE('%Y%m%d', date_first_visit),DAY) AS time FROM mortality_table WHERE device = 'mobile' ORDER BY DATE_DIFF(PARSE_DATE('%Y%m%d',date_event), PARSE_DATE('%Y%m%d', date_first_visit),DAY) DESC LIMIT 1",lite,bq268,ga_sessions_*.date; ga_sessions_*.device; ga_sessions_*.fullvisitorid; ga_sessions_*.hits,4,16,True,ok,False,bq268 sf_bq269,GA360,bigquery,"Between June 1, 2017, and July 31, 2017, consider only sessions that have non-null pageviews. Classify each session as ‘purchase’ if it has at least one transaction, or ‘non_purchase’ otherwise. For each month, sum each visitor’s total pageviews under each classification, then compute the average pageviews per visitor for both purchase and non-purchase groups in each month, and present the results side by side.","WITH visitor_pageviews AS ( SELECT FORMAT_DATE('%Y%m', PARSE_DATE('%Y%m%d', date)) AS month, CASE WHEN totals.transactions > 0 THEN 'purchase' ELSE 'non_purchase' END AS purchase_status, fullVisitorId, SUM(totals.pageviews) AS total_pageviews FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` WHERE _TABLE_SUFFIX BETWEEN '20170601' AND '20170731' AND totals.pageviews IS NOT NULL GROUP BY month, purchase_status, fullVisitorId ), avg_pageviews AS ( SELECT month, purchase_status, AVG(total_pageviews) AS avg_pageviews_per_visitor FROM visitor_pageviews GROUP BY month, purchase_status ) SELECT month, MAX(CASE WHEN purchase_status = 'purchase' THEN avg_pageviews_per_visitor END) AS avg_pageviews_purchase, MAX(CASE WHEN purchase_status = 'non_purchase' THEN avg_pageviews_per_visitor END) AS avg_pageviews_non_purchase FROM avg_pageviews GROUP BY month ORDER BY month",lite,bq269,ga_sessions_*.date; ga_sessions_*.fullvisitorid; ga_sessions_*.totals,3,16,True,ok,False,bq269 sf_bq270,GA360,bigquery,"What were the monthly add-to-cart and purchase conversion rates, calculated as a percentage of pageviews on product details, from January to March 2017?","WITH cte1 AS (SELECT CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))),'0', EXTRACT(MONTH FROM (PARSE_DATE('%Y%m%d', date)))) AS month, COUNT(hits.eCommerceAction.action_type) AS num_product_view FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST(hits) AS hits WHERE _table_suffix BETWEEN '0101' AND '0331' AND hits.eCommerceAction.action_type = '2' GROUP BY month), cte2 AS (SELECT CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))),'0', EXTRACT(MONTH FROM (PARSE_DATE('%Y%m%d', date)))) AS month, COUNT(hits.eCommerceAction.action_type) AS num_addtocart FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST(hits) AS hits WHERE _table_suffix BETWEEN '0101' AND '0331' AND hits.eCommerceAction.action_type = '3' GROUP BY month), cte3 AS (SELECT CONCAT(EXTRACT(YEAR FROM (PARSE_DATE('%Y%m%d', date))),'0', EXTRACT(MONTH FROM (PARSE_DATE('%Y%m%d', date)))) AS month, COUNT(hits.eCommerceAction.action_type) AS num_purchase FROM `bigquery-public-data.google_analytics_sample.ga_sessions_2017*`, UNNEST(hits) AS hits, UNNEST(hits.product) AS product WHERE _table_suffix BETWEEN '0101' AND '0331' AND hits.eCommerceAction.action_type = '6' AND product.productRevenue IS NOT NULL GROUP BY month) SELECT ROUND((num_addtocart/num_product_view * 100),2) AS add_to_cart_rate, ROUND((num_purchase/num_product_view * 100),2) AS purchase_rate FROM cte1 LEFT JOIN cte2 USING(month) LEFT JOIN cte3 USING(month) ORDER BY month;",lite,bq270,ga_sessions_*.date; ga_sessions_*.hits,2,16,True,ok,False,bq270 sf_bq271,THELOOK_ECOMMERCE,snowflake,"Please generate a report that, for each month in 2021, provides the number of orders, the number of unique purchasers, and the profit (calculated as the sum of product retail prices minus the sum of product costs), where the orders were placed during 2021 by users who registered in 2021 for inventory items created in 2021, and group the results by the users' country, product department, and product category.","SELECT TO_CHAR(DATE_TRUNC('month', TO_TIMESTAMP_LTZ(""ORDERS"".""created_at"" / 1000000)), 'YYYY-MM') AS ""order_month"", ""USERS"".""country"" AS ""country"", ""INVENTORY_ITEMS"".""product_department"" AS ""product_department"", ""INVENTORY_ITEMS"".""product_category"" AS ""product_category"", COUNT(DISTINCT ""ORDERS"".""order_id"") AS ""num_orders"", COUNT(DISTINCT ""ORDERS"".""user_id"") AS ""unique_purchasers"", SUM(COALESCE(""INVENTORY_ITEMS"".""product_retail_price"",0)) - SUM(COALESCE(""INVENTORY_ITEMS"".""cost"",0)) AS ""profit"" FROM ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""ORDERS"" ""ORDERS"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""USERS"" ""USERS"" ON ""ORDERS"".""user_id"" = ""USERS"".""id"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""ORDER_ITEMS"" ""ORDER_ITEMS"" ON ""ORDERS"".""order_id"" = ""ORDER_ITEMS"".""order_id"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""INVENTORY_ITEMS"" ""INVENTORY_ITEMS"" ON ""ORDER_ITEMS"".""inventory_item_id"" = ""INVENTORY_ITEMS"".""id"" WHERE ""ORDERS"".""created_at"" >= 1609459200000000 AND ""ORDERS"".""created_at"" < 1640995200000000 AND ""USERS"".""created_at"" >= 1609459200000000 AND ""USERS"".""created_at"" < 1640995200000000 AND ""INVENTORY_ITEMS"".""created_at"" >= 1609459200000000 AND ""INVENTORY_ITEMS"".""created_at"" < 1640995200000000 GROUP BY DATE_TRUNC('month', TO_TIMESTAMP_LTZ(""ORDERS"".""created_at"" / 1000000)), ""USERS"".""country"", ""INVENTORY_ITEMS"".""product_department"", ""INVENTORY_ITEMS"".""product_category"" ORDER BY ""order_month"", ""country"", ""product_department"", ""product_category"";",snow,sf_bq271,inventory_items.cost; inventory_items.created_at; inventory_items.id; inventory_items.product_category; inventory_items.product_department; inventory_items.product_retail_price; order_items.inventory_item_id; order_items.order_id; orders.created_at; orders.order_id; orders.user_id; users.country; users.created_at; users.id,14,73,True,ok,False,sf_bq271 sf_bq273,THELOOK_ECOMMERCE,snowflake,"Can you list the top 5 months from August 2022 to November 2023 where the profit from Facebook-sourced completed orders showed the largest month-over-month increase? Calculate profit as sales minus costs, group by delivery month, and include only orders created between August 2022 and November 2023. Compare each month's profit to its previous month to find the largest increases.","WITH ""order_profit"" AS ( SELECT CAST(DATE_TRUNC('month', TO_TIMESTAMP(""o"".""delivered_at"" / 1000000)) AS DATE) AS ""delivery_month"", ""o"".""order_id"", SUM(""oi"".""sale_price"" - COALESCE(""ii"".""cost"", 0)) AS ""order_profit"" FROM ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""ORDERS"" AS ""o"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""USERS"" AS ""u"" ON ""o"".""user_id"" = ""u"".""id"" JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""ORDER_ITEMS"" AS ""oi"" ON ""o"".""order_id"" = ""oi"".""order_id"" LEFT JOIN ""THELOOK_ECOMMERCE"".""THELOOK_ECOMMERCE"".""INVENTORY_ITEMS"" AS ""ii"" ON ""oi"".""inventory_item_id"" = ""ii"".""id"" WHERE ""o"".""status"" = 'Complete' AND ""u"".""traffic_source"" = 'Facebook' AND TO_TIMESTAMP(""o"".""created_at"" / 1000000) >= TO_TIMESTAMP('2022-08-01') AND TO_TIMESTAMP(""o"".""created_at"" / 1000000) < TO_TIMESTAMP('2023-12-01') AND ""o"".""delivered_at"" IS NOT NULL GROUP BY 1, 2 ), ""monthly_profit"" AS ( SELECT ""delivery_month"", SUM(""order_profit"") AS ""monthly_profit"" FROM ""order_profit"" WHERE ""delivery_month"" >= DATE '2022-08-01' AND ""delivery_month"" <= DATE '2023-11-01' GROUP BY 1 ), ""monthly_changes"" AS ( SELECT ""delivery_month"", ""monthly_profit"", ""monthly_profit"" - LAG(""monthly_profit"") OVER (ORDER BY ""delivery_month"") AS ""profit_increase"" FROM ""monthly_profit"" ) SELECT ""delivery_month"", ""monthly_profit"", ""profit_increase"" FROM ""monthly_changes"" WHERE ""profit_increase"" IS NOT NULL ORDER BY ""profit_increase"" DESC, ""delivery_month"" LIMIT 5",snow,sf_bq273,inventory_items.cost; inventory_items.id; order_items.inventory_item_id; order_items.order_id; order_items.sale_price; orders.created_at; orders.delivered_at; orders.order_id; orders.status; orders.user_id; users.id; users.traffic_source,12,73,True,ok,False,sf_bq273 sf_bq275,GA360,bigquery,Which visitor IDs belong to users whose first transaction occurred on a device explicitly labeled as 'mobile' on a later date than their first visit?,"WITH visit AS ( SELECT fullvisitorid, MIN(date) AS date_first_visit FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` GROUP BY fullvisitorid ), transactions AS ( SELECT fullvisitorid, MIN(date) AS date_transactions, 1 AS transaction FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` AS ga, UNNEST(ga.hits) AS hits WHERE hits.transaction.transactionId IS NOT NULL GROUP BY fullvisitorid ), device_transactions AS ( SELECT DISTINCT fullvisitorid, date, device.deviceCategory AS device_transaction FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*` AS ga, UNNEST(ga.hits) AS hits WHERE hits.transaction.transactionId IS NOT NULL ), visits_transactions AS ( SELECT visit.fullvisitorid, date_first_visit, date_transactions, device_transaction FROM visit LEFT JOIN transactions ON visit.fullvisitorid = transactions.fullvisitorid LEFT JOIN device_transactions ON visit.fullvisitorid = device_transactions.fullvisitorid AND transactions.date_transactions = device_transactions.date ) SELECT fullvisitorid FROM visits_transactions WHERE DATE_DIFF(PARSE_DATE('%Y%m%d', date_transactions), PARSE_DATE('%Y%m%d', date_first_visit), DAY) > 0 AND device_transaction = ""mobile"";",lite,bq275,ga_sessions_*.date; ga_sessions_*.device; ga_sessions_*.fullvisitorid; ga_sessions_*.hits,4,16,True,ok,False,bq275 sf_bq279,AUSTIN,bigquery,Can you provide the number of distinct active and closed bike share stations for each year 2013 and 2014?,"SELECT t.year, CASE WHEN t.year = 2013 THEN ( SELECT COUNT(DISTINCT station_id) FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` t INNER JOIN `bigquery-public-data.austin_bikeshare.bikeshare_stations` s ON t.start_station_id = s.station_id WHERE s.status = 'active' AND EXTRACT(YEAR FROM start_time) = 2013 ) WHEN t.year = 2014 THEN ( SELECT COUNT(DISTINCT station_id) FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` t INNER JOIN `bigquery-public-data.austin_bikeshare.bikeshare_stations` s ON t.start_station_id = s.station_id WHERE s.status = 'active' AND EXTRACT(YEAR FROM start_time) = 2014 ) END AS number_status_active, CASE WHEN t.year = 2013 THEN ( SELECT COUNT(DISTINCT station_id) FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` t INNER JOIN `bigquery-public-data.austin_bikeshare.bikeshare_stations` s ON t.start_station_id = s.station_id WHERE s.status = 'closed' AND EXTRACT(YEAR FROM start_time) = 2013 ) WHEN t.year = 2014 THEN ( SELECT COUNT(DISTINCT station_id) FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` t INNER JOIN `bigquery-public-data.austin_bikeshare.bikeshare_stations` s ON t.start_station_id = s.station_id WHERE s.status = 'closed' AND EXTRACT(YEAR FROM start_time) = 2014 ) END AS number_status_closed FROM ( SELECT EXTRACT(YEAR FROM start_time) AS year, start_station_id FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` ) AS t INNER JOIN `bigquery-public-data.austin_bikeshare.bikeshare_stations` s ON t.start_station_id = s.station_id WHERE t.year BETWEEN 2013 AND 2014 GROUP BY t.year ORDER BY t.year",lite,bq279,bikeshare_stations.station_id; bikeshare_stations.status; bikeshare_trips.start_station_id; bikeshare_trips.start_time,4,81,True,ok,False,bq279 sf_bq280,STACKOVERFLOW,bigquery,"Please provide the display name of the user who has answered the most questions on Stack Overflow, considering only users with a reputation greater than 10.","WITH UserAnswers AS ( SELECT owner_user_id AS answer_owner_id, COUNT(id) AS answer_count FROM bigquery-public-data.stackoverflow.posts_answers WHERE owner_user_id IS NOT NULL GROUP BY owner_user_id ), DetailedUsers AS ( SELECT id AS user_id, display_name AS user_display_name, reputation FROM bigquery-public-data.stackoverflow.users WHERE display_name IS NOT NULL AND reputation > 10 ), RankedUsers AS ( SELECT u.user_display_name, u.reputation, a.answer_count, ROW_NUMBER() OVER (ORDER BY a.answer_count DESC) AS rank FROM DetailedUsers u JOIN UserAnswers a ON u.user_id = a.answer_owner_id ) SELECT user_display_name, FROM RankedUsers WHERE rank = 1; ",lite,bq280,posts_*.id; posts_*.owner_user_id; users.display_name; users.id; users.reputation,5,376,True,fix,True,bq280 sf_bq281,AUSTIN,bigquery,"What is the highest number of electric bike rides lasting more than 10 minutes taken by subscribers with 'Student Membership' in a single day, excluding rides starting or ending at 'Mobile Station' or 'Repair Shop'?","SELECT COUNT(1) AS num_rides FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` WHERE start_station_name NOT IN ('Mobile Station', 'Repair Shop') AND end_station_name NOT IN ('Mobile Station', 'Repair Shop') AND subscriber_type = 'Student Membership' AND bike_type = 'electric' AND duration_minutes > 10 GROUP BY EXTRACT(YEAR from start_time), EXTRACT(MONTH from start_time), EXTRACT(DAY from start_time) ORDER BY num_rides DESC LIMIT 1",lite,bq281,bikeshare_trips.bike_type; bikeshare_trips.duration_minutes; bikeshare_trips.end_station_name; bikeshare_trips.start_station_name; bikeshare_trips.start_time; bikeshare_trips.subscriber_type,6,81,True,ok,False,bq281 sf_bq282,AUSTIN,bigquery,"Can you tell me the numeric value of the active council district in Austin which has the highest number of bike trips that start and end within the same district, but not at the same station?","SELECT district FROM ( SELECT S.starting_district AS district, T.start_station_id, T.end_station_id FROM `bigquery-public-data.austin_bikeshare.bikeshare_trips` AS T INNER JOIN ( SELECT station_id, council_district AS starting_district FROM `bigquery-public-data.austin_bikeshare.bikeshare_stations` WHERE status = ""active"" ) AS S ON T.start_station_id = S.station_id WHERE S.starting_district IN ( SELECT council_district FROM `bigquery-public-data.austin_bikeshare.bikeshare_stations` WHERE status = ""active"" AND station_id = SAFE_CAST(T.end_station_id AS INT64) ) AND T.start_station_id != SAFE_CAST(T.end_station_id AS INT64) ) GROUP BY district ORDER BY COUNT(*) DESC LIMIT 1; ",lite,bq282,bikeshare_stations.council_district; bikeshare_stations.station_id; bikeshare_stations.status; bikeshare_trips.end_station_id; bikeshare_trips.start_station_id,5,81,True,fix,False,bq282 sf_bq284,BBC,bigquery,"Can you provide a breakdown of the total number of articles into different categories and the percentage of those articles that mention ""education"" within each category from the BBC News?","SELECT category, COUNT(*) AS number_total_by_category, CASE WHEN category = 'tech' THEN (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE (LOWER(body) LIKE '%education%') AND category = 'tech') * 100 / (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE category = 'tech') WHEN category = 'sport' THEN (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE (LOWER(body) LIKE '%education%') AND category = 'sport') * 100 / (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE category = 'sport') WHEN category = 'business' THEN (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE (LOWER(body) LIKE '%education%') AND category = 'business') * 100 / (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE category = 'business') WHEN category = 'politics' THEN (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE (LOWER(body) LIKE '%education%') AND category = 'politics') * 100 / (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE category = 'politics') WHEN category = 'entertainment' THEN (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE (LOWER(body) LIKE '%education%') AND category = 'entertainment') * 100 / (SELECT count(*) FROM `bigquery-public-data.bbc_news.fulltext` WHERE category = 'entertainment') END AS percent_education FROM `bigquery-public-data.bbc_news.fulltext` GROUP BY category;",lite,bq284,fulltext.body; fulltext.category,2,4,True,ok,False,bq284 sf_bq285,FDA,bigquery,Could you provide me with the zip code of the location that has the highest number of bank institutions in Florida?,"with _fips AS ( SELECT state_fips_code FROM `bigquery-public-data.census_utility.fips_codes_states` WHERE state_name = ""Florida"" ) ,_zip AS ( SELECT z.zip_code, z.zip_code_geom, FROM `bigquery-public-data.geo_us_boundaries.zip_codes` z, _fips u WHERE z.state_fips_code = u.state_fips_code ) ,locations AS ( SELECT COUNT(i.institution_name) AS count_locations, l.zip_code FROM `bigquery-public-data.fdic_banks.institutions` i JOIN `bigquery-public-data.fdic_banks.locations` l USING (fdic_certificate_number) WHERE l.state IS NOT NULL AND l.state_name IS NOT NULL GROUP BY 2 ) SELECT z.zip_code FROM _zip z JOIN locations l USING (zip_code) GROUP BY z.zip_code ORDER BY SUM(l.count_locations) DESC LIMIT 1;",lite,bq285,fips_codes_states.state_fips_code; fips_codes_states.state_name; institutions.fdic_certificate_number; institutions.institution_name; institutions.state_fips_code; zip_codes.state_fips_code; zip_codes.state_name; zip_codes.zip_code,8,417,True,fix,True,bq285 sf_bq286,USA_NAMES,bigquery,"Can you tell me the name of the most popular female baby in Wyoming for the year 2021, based on the proportion of female babies given that name compared to the total number of female babies given the same name across all states?","SELECT a.name AS name FROM `bigquery-public-data.usa_names.usa_1910_current` a JOIN ( SELECT name, gender, year, SUM(number) AS total_number FROM `bigquery-public-data.usa_names.usa_1910_current` GROUP BY name, gender, year) b ON a.name = b.name AND a.gender = b.gender AND a.year = b.year WHERE a.gender = 'F' AND a.state = 'WY' AND a.year = 2021 ORDER BY (a.number / b.total_number) DESC LIMIT 1 ",lite,bq286,usa_1910_*.gender; usa_1910_*.name; usa_1910_*.number; usa_1910_*.state; usa_1910_*.year,5,5,True,ok,False,bq286 sf_bq289,GEO_OPENSTREETMAP_CENSUS_PLACES,snowflake,"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?","WITH philly_amenities AS ( SELECT ""p"".""osm_id"", TO_GEOGRAPHY(""p"".""geometry"") AS ""geo"" FROM ""GEO_OPENSTREETMAP_CENSUS_PLACES"".""GEO_US_CENSUS_PLACES"".""PLACES_PENNSYLVANIA"" AS ""pa"" JOIN ""GEO_OPENSTREETMAP_CENSUS_PLACES"".""GEO_OPENSTREETMAP"".""PLANET_FEATURES_POINTS"" AS ""p"" ON ST_CONTAINS(TO_GEOGRAPHY(""pa"".""place_geom""), TO_GEOGRAPHY(""p"".""geometry"")) , TABLE(FLATTEN(""p"".""all_tags"")) AS ""t"" WHERE ""pa"".""place_name"" = 'Philadelphia' AND ""t"".""VALUE"":""key""::STRING = 'amenity' AND ""t"".""VALUE"":""value""::STRING IN ('library', 'place_of_worship', 'community_centre') ) SELECT MIN(ST_DISTANCE(""a1"".""geo"", ""a2"".""geo"")) FROM philly_amenities AS ""a1"" CROSS JOIN philly_amenities AS ""a2"" WHERE ""a1"".""osm_id"" < ""a2"".""osm_id""",snow,sf_bq289,places_*.place_geom; places_*.place_name; planet_features_points.all_tags; planet_features_points.geometry; planet_features_points.osm_id,5,121,True,ok,False,sf_bq289 sf_bq290,NOAA_DATA,bigquery,"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?","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;",lite,bq290,gsod_*.date; gsod_*.stn; gsod_*.temp; gsod_*.wban; stations.country; stations.name; stations.usaf; stations.wban,8,745,True,fix,False,bq290 sf_bq291,NOAA_GLOBAL_FORECAST_SYSTEM,snowflake,"Can you provide a daily weather summary for July 2019 within a 5 km radius of latitude 26.75 and longitude 51.5? I need the maximum, minimum, and average temperatures; total precipitation; average cloud cover between 10 AM and 5 PM; total snowfall (when average temperature is below 32°F); and total rainfall (when average temperature is 32°F or above) for each forecast date. The data should correspond to forecasts created in July 2019 for the following day.","WITH ""pts"" AS ( SELECT ""creation_time"", TO_DATE(TO_TIMESTAMP_NTZ(""creation_time"" / 1000000)) AS ""creation_date"", ""forecast"", ""geography"", ""geography_polygon"" FROM ""NOAA_GLOBAL_FORECAST_SYSTEM"".""NOAA_GLOBAL_FORECAST_SYSTEM"".""NOAA_GFS0P25"" WHERE TO_DATE(TO_TIMESTAMP_NTZ(""creation_time"" / 1000000)) BETWEEN '2019-07-01' AND '2019-07-31' AND ( (TO_GEOGRAPHY(""geography"") IS NOT NULL AND ( ST_DISTANCE(TO_GEOGRAPHY(""geography""), TO_GEOGRAPHY('POINT(51.5 26.75)')) <= 5000 OR ST_DISTANCE(TO_GEOGRAPHY(""geography""), TO_GEOGRAPHY('POINT(26.75 51.5)')) <= 5000 )) OR (TO_GEOGRAPHY(""geography_polygon"") IS NOT NULL AND ( ST_CONTAINS(TO_GEOGRAPHY(""geography_polygon""), TO_GEOGRAPHY('POINT(51.5 26.75)')) OR ST_CONTAINS(TO_GEOGRAPHY(""geography_polygon""), TO_GEOGRAPHY('POINT(26.75 51.5)')) )) ) ), ""flat"" AS ( SELECT p.""creation_date"" AS ""creation_date"", TO_DATE(TO_TIMESTAMP_NTZ((""f"".""VALUE"":""time"")::NUMBER / 1000000)) AS ""forecast_date"", EXTRACT(HOUR FROM TO_TIMESTAMP_NTZ((""f"".""VALUE"":""time"")::NUMBER / 1000000)) AS ""forecast_hour"", (((""f"".""VALUE"":""temperature_2m_above_ground"")::FLOAT) * 9.0/5.0) + 32 AS ""temp_f"", COALESCE((""f"".""VALUE"":""total_precipitation_surface"")::FLOAT, 0) AS ""precip"", (""f"".""VALUE"":""total_cloud_cover_entire_atmosphere"")::FLOAT AS ""cloud_cover"" FROM ""pts"" p, LATERAL FLATTEN(input => p.""forecast"") AS ""f"" ), ""daily"" AS ( SELECT ""forecast_date"", MAX(""temp_f"") AS ""max_temp_f"", MIN(""temp_f"") AS ""min_temp_f"", AVG(""temp_f"") AS ""avg_temp_f"", SUM(""precip"") AS ""total_precipitation"", AVG(CASE WHEN ""forecast_hour"" BETWEEN 10 AND 17 THEN ""cloud_cover"" END) AS ""avg_cloud_cover_10am_5pm"" FROM ""flat"" WHERE ""forecast_date"" = DATEADD('day', 1, ""creation_date"") AND ""forecast_date"" BETWEEN '2019-07-01' AND '2019-07-31' GROUP BY ""forecast_date"" ) SELECT ""forecast_date"", ""max_temp_f"" AS ""max_temperature_f"", ""min_temp_f"" AS ""min_temperature_f"", ""avg_temp_f"" AS ""avg_temperature_f"", ""total_precipitation"", ""avg_cloud_cover_10am_5pm"", CASE WHEN ""avg_temp_f"" < 32 THEN ""total_precipitation"" ELSE 0 END AS ""total_snowfall"", CASE WHEN ""avg_temp_f"" >= 32 THEN ""total_precipitation"" ELSE 0 END AS ""total_rainfall"" FROM ""daily"" ORDER BY ""forecast_date"" ASC;",snow,sf_bq291,noaa_gfs0p25.creation_time; noaa_gfs0p25.forecast; noaa_gfs0p25.geography; noaa_gfs0p25.geography_polygon,4,90,True,ok,False,sf_bq291 sf_bq294,SAN_FRANCISCO_PLUS,snowflake,"Could you provide the details of the top 5 longest bike share trips that started between July 1, 2017, and December 31, 2017, including the trip ID, duration in seconds, start date, start station name, route (derived from start station name to end station name), bike number, subscriber type, member's birth year, the member's current age (calculated using the current year), an age classification based on whether the member is younger than 40, between 40 and 60, or older than 60, the member's gender, and the name of the region of the start station? Please exclude any trips where the start station name, member's birth year, or member's gender is not specified.","SELECT t.""trip_id"" AS ""trip_id"", t.""duration_sec"" AS ""duration_sec"", TO_TIMESTAMP_NTZ(t.""start_date"" / 1000000) AS ""start_date"", t.""start_station_name"" AS ""start_station_name"", (t.""start_station_name"" || ' - ' || t.""end_station_name"") AS ""route"", t.""bike_number"" AS ""bike_number"", t.""subscriber_type"" AS ""subscriber_type"", CAST(t.""member_birth_year"" AS INT) AS ""member_birth_year"", (EXTRACT(YEAR FROM CURRENT_DATE) - CAST(t.""member_birth_year"" AS INT)) AS ""age"", CASE WHEN (EXTRACT(YEAR FROM CURRENT_DATE) - CAST(t.""member_birth_year"" AS INT)) < 40 THEN 'Young (<40 Y.O)' WHEN (EXTRACT(YEAR FROM CURRENT_DATE) - CAST(t.""member_birth_year"" AS INT)) BETWEEN 40 AND 60 THEN 'Adult (40-60 Y.O)' ELSE 'Senior Adult (>60 Y.O)' END AS ""age_class"", t.""member_gender"" AS ""member_gender"", r.""name"" AS ""region_name"" FROM ""SAN_FRANCISCO_PLUS"".""SAN_FRANCISCO_BIKESHARE"".""BIKESHARE_TRIPS"" t LEFT JOIN ""SAN_FRANCISCO_PLUS"".""SAN_FRANCISCO_BIKESHARE"".""BIKESHARE_STATION_INFO"" si ON si.""station_id"" = CAST(t.""start_station_id"" AS VARCHAR) LEFT JOIN ""SAN_FRANCISCO_PLUS"".""SAN_FRANCISCO_BIKESHARE"".""BIKESHARE_REGIONS"" r ON r.""region_id"" = si.""region_id"" WHERE t.""start_station_name"" IS NOT NULL AND TRIM(t.""start_station_name"") != '' AND t.""member_birth_year"" IS NOT NULL AND t.""member_gender"" IS NOT NULL AND TRIM(t.""member_gender"") != '' AND TO_TIMESTAMP_NTZ(t.""start_date"" / 1000000) BETWEEN TO_TIMESTAMP_NTZ('2017-07-01 00:00:00') AND TO_TIMESTAMP_NTZ('2017-12-31 23:59:59') ORDER BY t.""duration_sec"" DESC LIMIT 5;",snow,sf_bq294,bikeshare_regions.name; bikeshare_regions.region_id; bikeshare_station_info.region_id; bikeshare_station_info.station_id; bikeshare_trips.bike_number; bikeshare_trips.duration_sec; bikeshare_trips.end_station_name; bikeshare_trips.member_birth_year; bikeshare_trips.member_gender; bikeshare_trips.start_date; bikeshare_trips.start_station_id; bikeshare_trips.start_station_name; bikeshare_trips.subscriber_type; bikeshare_trips.trip_id,14,556,True,ok,False,sf_bq294 sf_bq295,GITHUB_REPOS_DATE,snowflake,"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?","SELECT w.""repo"":name::VARCHAR as repo_name, COUNT(*) as watch_count FROM ""GITHUB_REPOS_DATE"".""YEAR"".""_2017"" w WHERE w.""type"" = 'WatchEvent' AND w.""repo"" IS NOT NULL AND EXISTS ( SELECT 1 FROM ""GITHUB_REPOS_DATE"".""GITHUB_REPOS"".""SAMPLE_CONTENTS"" c WHERE c.""sample_repo_name"" = w.""repo"":name::VARCHAR AND c.""sample_path"" LIKE '%.py' AND c.""size"" < 15000 AND c.""content"" LIKE '%def %' ) GROUP BY repo_name ORDER BY watch_count DESC LIMIT 3;",snow,sf_bq295,_20_*.repo; _20_*.type; sample_contents.content; sample_contents.sample_path; sample_contents.sample_repo_name; sample_contents.size,6,43,True,ok,False,sf_bq295 sf_bq300,STACKOVERFLOW,bigquery,"What is the highest number of answers received for a single Python 2 specific question on Stack Overflow, excluding any discussions that involve Python 3?","WITH python2_questions AS ( SELECT q.id AS question_id, q.title, q.body AS question_body, q.tags FROM `bigquery-public-data.stackoverflow.posts_questions` q WHERE (LOWER(q.tags) LIKE '%python-2%' OR LOWER(q.tags) LIKE '%python-2.x%' OR ( LOWER(q.title) LIKE '%python 2%' OR LOWER(q.body) LIKE '%python 2%' OR LOWER(q.title) LIKE '%python2%' OR LOWER(q.body) LIKE '%python2%' )) AND ( LOWER(q.title) NOT LIKE '%python 3%' AND LOWER(q.body) NOT LIKE '%python 3%' AND LOWER(q.title) NOT LIKE '%python3%' AND LOWER(q.body) NOT LIKE '%python3%' ) ) SELECT COUNT(*) AS count_number FROM python2_questions q LEFT JOIN `bigquery-public-data.stackoverflow.posts_answers` a ON q.question_id = a.parent_id GROUP BY q.question_id ORDER BY count_number DESC LIMIT 1 ",lite,bq300,posts_*.body; posts_*.id; posts_*.parent_id; posts_*.tags; posts_*.title,5,376,True,ok,False,bq300 sf_bq301,STACKOVERFLOW,bigquery,"Retrieve details of accepted answers to Stack Overflow questions posted in January 2016 that have tags including ""javascript"" and at least one of ""xss"", ""cross-site"", ""exploit"", or ""cybersecurity""; the answers themselves must also have been posted in January 2016. For each accepted answer, include the answer's ID, the answerer's reputation, score, and comment count, along with the associated question's tags, score, answer count, the asker's reputation, view count, and comment count.","SELECT answer.id AS a_id, (SELECT users.reputation FROM `bigquery-public-data.stackoverflow.users` users WHERE users.id = answer.owner_user_id) AS a_user_reputation, answer.score AS a_score, answer.comment_count AS answer_comment_count, questions.tags as q_tags, questions.score AS q_score, questions.answer_count AS answer_count, (SELECT users.reputation FROM `bigquery-public-data.stackoverflow.users` users WHERE users.id = questions.owner_user_id) AS q_user_reputation, questions.view_count AS q_view_count, questions.comment_count AS q_comment_count FROM `bigquery-public-data.stackoverflow.posts_answers` AS answer LEFT JOIN `bigquery-public-data.stackoverflow.posts_questions` AS questions ON answer.parent_id = questions.id WHERE answer.id = questions.accepted_answer_id AND ( questions.tags LIKE '%javascript%' AND (questions.tags LIKE '%xss%' OR questions.tags LIKE '%cross-site%' OR questions.tags LIKE '%exploit%' OR questions.tags LIKE '%cybersecurity%') ) AND DATE(questions.creation_date) BETWEEN '2016-01-01' AND '2016-01-31' AND DATE(answer.creation_date) BETWEEN '2016-01-01' AND '2016-01-31' ",lite,bq301,posts_*.accepted_answer_id; posts_*.answer_count; posts_*.comment_count; posts_*.creation_date; posts_*.id; posts_*.owner_user_id; posts_*.parent_id; posts_*.score; posts_*.tags; posts_*.view_count; users.id; users.reputation,12,376,True,ok,False,bq301 sf_bq302,STACKOVERFLOW,bigquery,What is the monthly proportion of Stack Overflow questions tagged with 'python' in the year 2022?,"WITH -- Get recent data RecentData AS ( SELECT FORMAT_TIMESTAMP('%Y%m', creation_date) AS month_index, tags FROM `bigquery-public-data.stackoverflow.posts_questions` WHERE EXTRACT(YEAR FROM DATE(creation_date)) = 2022 ), -- Monthly number of questions posted MonthlyQuestions AS ( SELECT month_index, COUNT(*) AS num_questions FROM RecentData GROUP BY month_index ), -- Monthly number of questions posted with specific tags TaggedQuestions AS ( SELECT month_index, tag, COUNT(*) AS num_tags FROM RecentData, UNNEST(SPLIT(tags, '|')) AS tag WHERE tag IN ('python') GROUP BY month_index, tag ) SELECT a.month_index, a.num_tags / b.num_questions AS proportion FROM TaggedQuestions a LEFT JOIN MonthlyQuestions b ON a.month_index = b.month_index ORDER BY a.month_index, proportion DESC;",lite,bq302,posts_*.creation_date; posts_*.tags,2,376,True,ok,False,bq302 sf_bq303,STACKOVERFLOW,bigquery,"From July 1, 2019 through December 31, 2019, for all users with IDs between 16712208 and 18712208 on Stack Overflow, retrieve the user ID and the tags of the relevant question for each of their contributions, including comments on both questions and answers, any answers they posted, and any questions they authored, making sure to correctly associate the comment or answer with its parent question’s tags.","SELECT u_id, tags FROM ( -- select comments with tags from the post SELECT cm.u_id, cm.creation_date, cm.text, pq.tags, ""comment"" as type FROM ( SELECT a.parent_id as q_id, c.user_id as u_id, c.creation_date as creation_date, c.text as text FROM `bigquery-public-data.stackoverflow.comments` as c INNER JOIN `bigquery-public-data.stackoverflow.posts_answers` as a ON (a.id = c.post_id) WHERE c.user_id BETWEEN 16712208 AND 18712208 AND DATE(c.creation_date) BETWEEN '2019-07-01' AND '2019-12-31' UNION ALL SELECT q.id as q_id, c.user_id as u_id, c.creation_date as creation_date, c.text as text FROM `bigquery-public-data.stackoverflow.comments` as c INNER JOIN `bigquery-public-data.stackoverflow.posts_questions` as q ON (q.id = c.post_id) WHERE c.user_id BETWEEN 16712208 AND 18712208 AND DATE(c.creation_date) BETWEEN '2019-07-01' AND '2019-12-31' ) as cm INNER JOIN `bigquery-public-data.stackoverflow.posts_questions` as pq ON (pq.id = cm.q_id) UNION ALL -- select answers with tags related to the post SELECT pa.owner_user_id as u_id, pa.creation_date as creation_date, pa.body as text, pq.tags as tags, ""answer"" as type FROM `bigquery-public-data.stackoverflow.posts_answers` as pa LEFT OUTER JOIN `bigquery-public-data.stackoverflow.posts_questions` as pq ON pq.id = pa.parent_id WHERE pa.owner_user_id BETWEEN 16712208 AND 18712208 AND DATE(pa.creation_date) BETWEEN '2019-07-01' AND '2019-12-31' UNION ALL -- select posts SELECT pq.owner_user_id as u_id, pq.creation_date as creation_date, pq.body as text, pq.tags as tags, ""question"" as type FROM `bigquery-public-data.stackoverflow.posts_questions` as pq WHERE pq.owner_user_id BETWEEN 16712208 AND 18712208 AND DATE(pq.creation_date) BETWEEN '2019-07-01' AND '2019-12-31' ) ORDER BY u_id, creation_date; ",lite,bq303,comments.creation_date; comments.post_id; comments.text; comments.user_id; posts_*.body; posts_*.creation_date; posts_*.id; posts_*.owner_user_id; posts_*.parent_id; posts_*.tags,10,376,True,fix,True,bq303 sf_bq304,STACKOVERFLOW,bigquery,"Retrieve the top 50 most viewed questions for each of the following Android-related tags on StackOverflow: 'android-layout', 'android-activity', 'android-intent', 'android-edittext', 'android-fragments', 'android-recyclerview', 'listview', 'android-actionbar', 'google-maps', and 'android-asynctask'. Each question must contain the word 'how' in either its title or body and must not contain any of the following troubleshooting terms in either its title or body: 'fail', 'problem', 'error', 'wrong', 'fix', 'bug', 'issue', 'solve', or 'trouble'. Only include tags that have at least 50 questions meeting these criteria, and for each such tag, select the top 50 questions ranked by view count.","WITH tags_to_use AS ( SELECT tag, idx FROM UNNEST([ 'android-layout', 'android-activity', 'android-intent', 'android-edittext', 'android-fragments', 'android-recyclerview', 'listview', 'android-actionbar', 'google-maps', 'android-asynctask' ]) AS tag WITH OFFSET idx ), android_how_to_questions AS ( SELECT PQ.* FROM bigquery-public-data.stackoverflow.posts_questions PQ WHERE EXISTS ( SELECT 1 FROM UNNEST(SPLIT(PQ.tags, '|')) tag WHERE tag IN (SELECT tag FROM tags_to_use) ) AND (LOWER(PQ.title) LIKE '%how%' OR LOWER(PQ.body) LIKE '%how%') AND NOT (LOWER(PQ.title) LIKE '%fail%' OR LOWER(PQ.title) LIKE '%problem%' OR LOWER(PQ.title) LIKE '%error%' OR LOWER(PQ.title) LIKE '%wrong%' OR LOWER(PQ.title) LIKE '%fix%' OR LOWER(PQ.title) LIKE '%bug%' OR LOWER(PQ.title) LIKE '%issue%' OR LOWER(PQ.title) LIKE '%solve%' OR LOWER(PQ.title) LIKE '%trouble%') AND NOT (LOWER(PQ.body) LIKE '%fail%' OR LOWER(PQ.body) LIKE '%problem%' OR LOWER(PQ.body) LIKE '%error%' OR LOWER(PQ.body) LIKE '%wrong%' OR LOWER(PQ.body) LIKE '%fix%' OR LOWER(PQ.body) LIKE '%bug%' OR LOWER(PQ.body) LIKE '%issue%' OR LOWER(PQ.body) LIKE '%solve%' OR LOWER(PQ.body) LIKE '%trouble%') ), questions_with_tag_rankings AS ( SELECT T.id AS tag_id, TTU.idx AS tag_offset, T.tag_name, T.wiki_post_id AS tag_wiki_post_id, Q.id AS question_id, Q.title, Q.tags, Q.view_count, RANK() OVER (PARTITION BY T.id ORDER BY Q.view_count DESC) AS question_view_count_rank, COUNT(*) OVER (PARTITION BY T.id) AS total_valid_questions FROM bigquery-public-data.stackoverflow.tags T INNER JOIN tags_to_use TTU ON T.tag_name = TTU.tag INNER JOIN android_how_to_questions Q ON T.tag_name IN UNNEST(SPLIT(Q.tags, '|')) ) SELECT question_id FROM questions_with_tag_rankings WHERE question_view_count_rank <= 50 AND total_valid_questions >= 50 ORDER BY tag_offset ASC, question_view_count_rank ASC; ",lite,bq304,posts_*.body; posts_*.id; posts_*.tags; posts_*.title; posts_*.view_count; tags.id; tags.tag_name; tags.wiki_post_id,8,376,True,ok,False,bq304 sf_bq308,STACKOVERFLOW,bigquery,"Show the number of Stack Overflow questions asked each day of the week in 2021, and find out how many and what percentage of those were answered within one hour.","SELECT Day_of_Week, COUNT(1) AS Num_Questions, SUM(answered_in_1h) AS Num_Answered_in_1H, ROUND(100 * SUM(answered_in_1h) / COUNT(1),1) AS Percent_Answered_in_1H FROM ( SELECT q.id AS question_id, EXTRACT(DAYOFWEEK FROM q.creation_date) AS day_of_week, MAX(IF(a.parent_id IS NOT NULL AND (UNIX_SECONDS(a.creation_date)-UNIX_SECONDS(q.creation_date))/(60*60) <= 1, 1, 0)) AS answered_in_1h FROM `bigquery-public-data.stackoverflow.posts_questions` q LEFT JOIN `bigquery-public-data.stackoverflow.posts_answers` a ON q.id = a.parent_id WHERE EXTRACT(YEAR FROM a.creation_date) = 2020 AND EXTRACT(YEAR FROM q.creation_date) = 2020 GROUP BY question_id, day_of_week ) GROUP BY Day_of_Week ORDER BY Day_of_Week;",lite,bq308,posts_*.creation_date; posts_*.id; posts_*.parent_id,3,376,True,ok,False,bq308 sf_bq309,STACKOVERFLOW,bigquery,"Retrieve the top 10 longest questions on Stack Overflow, measured by the length of their body text, where each question either has an accepted answer or has no accepted answer but has at least one answer with a score-to-view ratio exceeding 0.01. For each of these questions, include the reputation of the user who asked the question, the user's net votes (calculated as their total up_votes minus down_votes), and the total number of badges the user has earned.","WITH badge_counts AS ( SELECT c.id, COUNT(DISTINCT d.id) AS badge_number FROM `bigquery-public-data.stackoverflow.users` AS c JOIN `bigquery-public-data.stackoverflow.badges` AS d ON c.id = d.user_id GROUP BY c.id ), labeled_questions AS ( SELECT a.id, IF( a.id IN ( SELECT DISTINCT b.id FROM `bigquery-public-data.stackoverflow.posts_answers` AS a JOIN `bigquery-public-data.stackoverflow.posts_questions` AS b ON a.parent_id = b.id WHERE b.accepted_answer_id IS NULL AND a.score / b.view_count > 0.01 ) OR accepted_answer_id IS NOT NULL, 1, 0 ) AS label, a.owner_user_id, LENGTH(a.body) AS body_length FROM `bigquery-public-data.stackoverflow.posts_questions` AS a ) SELECT lq.id, b.reputation, b.up_votes - b.down_votes AS net_votes, e.badge_number FROM labeled_questions AS lq JOIN `bigquery-public-data.stackoverflow.users` AS b ON lq.owner_user_id = b.id JOIN badge_counts AS e ON b.id = e.id WHERE lq.label = 1 ORDER BY lq.body_length DESC LIMIT 10; ",lite,bq309,badges.id; badges.user_id; posts_*.accepted_answer_id; posts_*.body; posts_*.id; posts_*.owner_user_id; posts_*.parent_id; posts_*.score; posts_*.view_count; users.down_votes; users.id; users.reputation; users.up_votes,13,376,True,fix,True,bq309 sf_bq310,STACKOVERFLOW,bigquery,"What is the title of the most viewed ""how"" question related to Android development on StackOverflow, across specified tags such as 'android-layout', 'android-activity', 'android-intent', and others","WITH tags_to_use AS ( SELECT tag, idx FROM UNNEST([ 'android-layout', 'android-activity', 'android-intent', 'android-edittext', 'android-fragments', 'android-recyclerview', 'listview', 'android-actionbar', 'google-maps', 'android-asynctask' ]) AS tag WITH OFFSET idx ), android_how_to_questions AS ( SELECT PQ.* FROM `bigquery-public-data.stackoverflow.posts_questions` PQ WHERE EXISTS ( SELECT 1 FROM UNNEST(SPLIT(PQ.tags, '|')) tag WHERE tag IN (SELECT tag FROM tags_to_use) ) AND (LOWER(PQ.title) LIKE '%how%' OR LOWER(PQ.body) LIKE '%how%') ), most_viewed_question AS ( SELECT T.id AS tag_id, T.tag_name, Q.id AS question_id, Q.title, Q.tags, Q.view_count FROM `bigquery-public-data.stackoverflow.tags` T INNER JOIN tags_to_use TTU ON T.tag_name = TTU.tag INNER JOIN android_how_to_questions Q ON T.tag_name IN UNNEST(SPLIT(Q.tags, '|')) ORDER BY Q.view_count DESC LIMIT 1 ) SELECT title FROM most_viewed_question;",lite,bq310,posts_*.body; posts_*.id; posts_*.tags; posts_*.title; posts_*.view_count; tags.id; tags.tag_name,7,376,True,ok,False,bq310 sf_bq320,IDC,snowflake,"In the dicom_pivot table, how many unique StudyInstanceUID values exactly match the SegmentedPropertyTypeCodeSequence of ""15825003"" (case-insensitive) and also have a collection_id of either ""Community"" or ""nsclc_radiomics""?","SELECT COUNT(DISTINCT ""StudyInstanceUID"") AS ""unique_study_count"" FROM ""IDC"".""IDC_V17"".""DICOM_PIVOT"" WHERE ""SegmentedPropertyTypeCodeSequence"" IS NOT NULL AND LOWER(TRIM(""SegmentedPropertyTypeCodeSequence"")) = '15825003' AND LOWER(TRIM(""collection_id"")) IN ('community', 'nsclc_radiomics');",snow,sf_bq320,dicom_pivot.collection_id; dicom_pivot.segmentedpropertytypecodesequence; dicom_pivot.studyinstanceuid,3,2100,True,ok,False,sf_bq320 sf_bq321,IDC,snowflake,"How many unique StudyInstanceUIDs are there from the DWI, T2 Weighted Axial, Apparent Diffusion Coefficient series, and T2 Weighted Axial Segmentations in the 'qin_prostate_repeatability' collection?","SELECT COUNT(DISTINCT ""StudyInstanceUID"") AS ""unique_study_count"" FROM ""IDC"".""IDC_V17"".""DICOM_PIVOT"" WHERE ""collection_id"" = 'qin_prostate_repeatability' AND ""SeriesDescription"" IN ( 'DWI', 'T2 Weighted Axial', 'Apparent Diffusion Coefficient', 'T2 Weighted Axial Segmentations' );",snow,sf_bq321,dicom_pivot.collection_id; dicom_pivot.seriesdescription; dicom_pivot.studyinstanceuid,3,2100,True,ok,False,sf_bq321 sf_bq327,WORLD_BANK,bigquery,"How many debt indicators for Russia have a value of 0, excluding NULL values?","WITH russia_Data AS ( SELECT DISTINCT id.country_name, id.value, -- Format in DataStudio id.indicator_name FROM ( SELECT country_code, region FROM bigquery-public-data.world_bank_intl_debt.country_summary WHERE region != """" -- Aggregated countries do not have a region ) cs -- Aggregated countries do not have a region INNER JOIN ( SELECT country_code, country_name, value, indicator_name FROM bigquery-public-data.world_bank_intl_debt.international_debt WHERE country_code = 'RUS' ) id ON cs.country_code = id.country_code WHERE value IS NOT NULL ) -- Count the number of indicators with a value of 0 for Russia SELECT COUNT(*) AS number_of_indicators_with_zero FROM russia_Data WHERE value = 0;",lite,bq327,country_summary.country_code; country_summary.region; international_*.country_code; international_*.country_name; international_*.indicator_name; international_*.value,6,144,True,ok,False,bq327 sf_bq328,WORLD_BANK,bigquery,Which region has the highest median GDP (constant 2015 US$) value?,"WITH country_data AS ( -- CTE for country descriptive data SELECT country_code, short_name AS country, region, income_group FROM `bigquery-public-data.world_bank_wdi.country_summary` ), gdp_data AS ( -- Filter data to only include GDP values SELECT data.country_code, country, region, value AS gdp_value FROM `bigquery-public-data.world_bank_wdi.indicators_data` data LEFT JOIN country_data ON data.country_code = country_data.country_code WHERE indicator_code = ""NY.GDP.MKTP.KD"" -- GDP Indicator AND country_data.region IS NOT NULL AND country_data.income_group IS NOT NULL ), cal_median_gdp AS ( -- Calculate the median GDP value for each region SELECT region, APPROX_QUANTILES(gdp_value, 2)[OFFSET(1)] AS median_gdp FROM gdp_data GROUP BY region ) -- Select the regions with their median GDP values SELECT region FROM cal_median_gdp ORDER BY median_gdp DESC LIMIT 1;",lite,bq328,country_summary.country_code; country_summary.income_group; country_summary.region; country_summary.short_name; indicators_data.country_code; indicators_data.indicator_code; indicators_data.value,7,144,True,fix,False,bq328 sf_bq330,FDA,bigquery,"Which Colorado zip code has the highest concentration of bank locations per block group, based on the overlap between zip codes and block groups?","WITH _fips AS ( SELECT state_fips_code FROM `bigquery-public-data.census_utility.fips_codes_states` WHERE state_name = ""Colorado"" ), _bg AS ( SELECT b.geo_id, b.blockgroup_geom, ST_AREA(b.blockgroup_geom) AS bg_size FROM `bigquery-public-data.geo_census_blockgroups.us_blockgroups_national` b JOIN _fips u ON b.state_fips_code = u.state_fips_code ), _zip AS ( SELECT z.zip_code, z.zip_code_geom FROM `bigquery-public-data.geo_us_boundaries.zip_codes` z JOIN _fips u ON z.state_fips_code = u.state_fips_code ), bq_zip_overlap AS ( SELECT b.geo_id, z.zip_code, ST_AREA(ST_INTERSECTION(b.blockgroup_geom, z.zip_code_geom)) / b.bg_size AS overlap_size, b.blockgroup_geom FROM _zip z JOIN _bg b ON ST_INTERSECTS(b.blockgroup_geom, z.zip_code_geom) ), locations AS ( SELECT SUM(overlap_size * count_locations) AS locations_per_bg, l.zip_code FROM ( SELECT COUNT(CONCAT(institution_name, "" : "", branch_name)) AS count_locations, zip_code FROM `bigquery-public-data.fdic_banks.locations` WHERE state IS NOT NULL AND state_name IS NOT NULL GROUP BY zip_code ) l JOIN bq_zip_overlap ON l.zip_code = bq_zip_overlap.zip_code GROUP BY l.zip_code ) SELECT l.zip_code FROM locations l GROUP BY l.zip_code ORDER BY MAX(locations_per_bg) DESC LIMIT 1;",lite,bq330,fips_codes_states.state_fips_code; fips_codes_states.state_name; locations.state_name; us_blockgroups_national.blockgroup_geom; us_blockgroups_national.geo_id; us_blockgroups_national.state_fips_code; zip_codes.state_fips_code; zip_codes.zip_code; zip_codes.zip_code_geom,9,417,True,fix,True,bq330 sf_bq334,CRYPTO,snowflake,"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.","WITH ""merged_union"" AS ( SELECT ""block_timestamp"", ""value"", 'output' AS ""origin"" FROM ""CRYPTO"".""CRYPTO_BITCOIN"".""OUTPUTS"" UNION ALL SELECT ""block_timestamp"", ""value"", 'input' AS ""origin"" FROM ""CRYPTO"".""CRYPTO_BITCOIN"".""INPUTS"" ), ""merged_outputs_avg"" AS ( SELECT DATE_PART(year, TO_TIMESTAMP_NTZ(""block_timestamp"", 6)) AS ""year"", AVG(""value"") AS ""merged_avg"" FROM ""merged_union"" WHERE ""origin"" = 'output' AND ""value"" IS NOT NULL AND ""block_timestamp"" IS NOT NULL GROUP BY 1 ), ""transactions_avg"" AS ( SELECT DATE_PART(year, TO_TIMESTAMP_NTZ(""block_timestamp"", 6)) AS ""year"", AVG(""output_value"") AS ""tx_avg"" FROM ""CRYPTO"".""CRYPTO_BITCOIN"".""TRANSACTIONS"" WHERE ""output_value"" IS NOT NULL AND ""block_timestamp"" IS NOT NULL GROUP BY 1 ) SELECT m.""year"", m.""merged_avg"" - t.""tx_avg"" AS ""difference"" FROM ""merged_outputs_avg"" m JOIN ""transactions_avg"" t ON m.""year"" = t.""year"" ORDER BY m.""year"";",snow,sf_bq334,inputs.block_timestamp; inputs.value; outputs.block_timestamp; outputs.value; transactions.block_timestamp; transactions.output_value,6,286,True,ok,False,sf_bq334 sf_bq338,CENSUS_BUREAU_ACS_1,bigquery,"Can you find the census tracts in the 36047 area that are among the top 20 for the largest percentage increases in population from 2011 to 2018, are also among the top 20 for the largest absolute increases in median income during the same period, and had over 1,000 residents in each of those years?","WITH population_change AS ( SELECT a.geo_id, a.total_pop AS pop_2011, b.total_pop AS pop_2018, ((b.total_pop - a.total_pop) / a.total_pop) * 100 AS population_change_percentage FROM bigquery-public-data.census_bureau_acs.censustract_2011_5yr a JOIN bigquery-public-data.census_bureau_acs.censustract_2018_5yr b ON a.geo_id = b.geo_id WHERE a.total_pop > 1000 AND b.total_pop > 1000 AND a.geo_id LIKE '36047%' AND b.geo_id LIKE '36047%' ORDER BY population_change_percentage DESC LIMIT 20 ), acs_2018 AS ( SELECT geo_id, median_income AS median_income_2018 FROM bigquery-public-data.census_bureau_acs.censustract_2018_5yr WHERE geo_id LIKE '36047%' AND total_pop > 1000 ), acs_2011 AS ( SELECT geo_id, median_income AS median_income_2011 FROM bigquery-public-data.census_bureau_acs.censustract_2011_5yr WHERE geo_id LIKE '36047%' AND total_pop > 1000 ), acs_diff AS ( SELECT a18.geo_id, a18.median_income_2018, a11.median_income_2011, (a18.median_income_2018 - a11.median_income_2011) AS median_income_diff FROM acs_2018 a18 JOIN acs_2011 a11 ON a18.geo_id = a11.geo_id WHERE (a18.median_income_2018 - a11.median_income_2011) IS NOT NULL ORDER BY (a18.median_income_2018 - a11.median_income_2011) DESC LIMIT 20 ), common_geoids AS ( SELECT population_change.geo_id FROM population_change JOIN acs_diff ON population_change.geo_id = acs_diff.geo_id ) SELECT geo_id FROM common_geoids; ",lite,bq338,censustract_*.geo_id; censustract_*.median_income; censustract_*.total_pop,3,5421,True,ok,False,bq338 sf_bq339,SAN_FRANCISCO_PLUS,bigquery,"Which month in 2017 had the largest absolute difference between cumulative bike usage minutes for customers and subscribers? Which month (in number) in 2017 had the largest absolute difference between cumulative bike usage minutes (in thousands) for customers and subscribers, based on the trip end dates in the San Francisco bikeshare data?","WITH monthly_totals AS ( SELECT SUM(CASE WHEN subscriber_type = 'Customer' THEN duration_sec / 60 ELSE NULL END) AS customer_minutes_sum, SUM(CASE WHEN subscriber_type = 'Subscriber' THEN duration_sec / 60 ELSE NULL END) AS subscriber_minutes_sum, EXTRACT(MONTH FROM end_date) AS end_month FROM `bigquery-public-data.san_francisco_bikeshare.bikeshare_trips` WHERE EXTRACT(YEAR FROM end_date) = 2017 GROUP BY end_month ), cumulative_totals AS ( SELECT end_month, SUM(customer_minutes_sum) OVER (ORDER BY end_month ROWS UNBOUNDED PRECEDING) / 1000 AS cumulative_minutes_cust, SUM(subscriber_minutes_sum) OVER (ORDER BY end_month ROWS UNBOUNDED PRECEDING) / 1000 AS cumulative_minutes_sub FROM monthly_totals ), differences AS ( SELECT end_month, ABS(cumulative_minutes_cust - cumulative_minutes_sub) AS abs_diff FROM cumulative_totals ) SELECT end_month FROM differences ORDER BY abs_diff DESC LIMIT 1;",lite,bq339,bikeshare_trips.duration_sec; bikeshare_trips.end_date; bikeshare_trips.subscriber_type,3,556,True,ok,False,bq339 sf_bq341,CRYPTO,snowflake,"Which Ethereum address has the top 3 smallest positive balance from transactions involving the token at address ""0xa92a861fc11b99b24296af880011b47f9cafb5ab""?","WITH address_balances AS ( SELECT address, SUM(CASE WHEN direction = 'in' THEN value_numeric ELSE -value_numeric END) AS balance FROM ( SELECT ""to_address"" AS address, CAST(""value"" AS NUMBER(38,0)) AS value_numeric, 'in' AS direction FROM CRYPTO.CRYPTO_ETHEREUM.TOKEN_TRANSFERS WHERE ""token_address"" = '0xa92a861fc11b99b24296af880011b47f9cafb5ab' UNION ALL SELECT ""from_address"" AS address, CAST(""value"" AS NUMBER(38,0)) AS value_numeric, 'out' AS direction FROM CRYPTO.CRYPTO_ETHEREUM.TOKEN_TRANSFERS WHERE ""token_address"" = '0xa92a861fc11b99b24296af880011b47f9cafb5ab' ) WHERE address != '0x0000000000000000000000000000000000000000' GROUP BY address ) SELECT address FROM address_balances WHERE balance > 0 ORDER BY balance ASC LIMIT 3",snow,sf_bq341,token_transfers.from_address; token_transfers.to_address; token_transfers.token_address; token_transfers.value,4,286,True,ok,False,sf_bq341 sf_bq345,IDC,snowflake,"How large are the DICOM image files with SEG or RTSTRUCT modalities and the SOP Class UID ""1.2.840.10008.5.1.4.1.1.66.4"", when grouped by collection, study, and series IDs, if they have no references to other series, images, or sources? Can you also provide a viewer URL formatted as ""https://viewer.imaging.datacommons.cancer.gov/viewer/"" followed by the study ID, and list these sizes in kilobytes, sorted from largest to smallest?","SELECT ""collection_id"", ""StudyInstanceUID"" AS ""study_id"", ""SeriesInstanceUID"" AS ""series_id"", 'https://viewer.imaging.datacommons.cancer.gov/viewer/' || ""StudyInstanceUID"" AS ""viewer_url"", ROUND(SUM(""instance_size"") / 1024) AS ""size_kb"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" WHERE ""Modality"" IN ('SEG','RTSTRUCT') AND ""SOPClassUID"" = '1.2.840.10008.5.1.4.1.1.66.4' AND COALESCE(ARRAY_SIZE(""ReferencedSeriesSequence""), 0) = 0 AND COALESCE(ARRAY_SIZE(""ReferencedImageSequence""), 0) = 0 AND COALESCE(ARRAY_SIZE(""SourceImageSequence""), 0) = 0 GROUP BY ""collection_id"", ""StudyInstanceUID"", ""SeriesInstanceUID"", 'https://viewer.imaging.datacommons.cancer.gov/viewer/' || ""StudyInstanceUID"" ORDER BY ""size_kb"" DESC;",snow,sf_bq345,dicom_all.collection_id; dicom_all.instance_size; dicom_all.modality; dicom_all.referencedimagesequence; dicom_all.referencedseriessequence; dicom_all.seriesinstanceuid; dicom_all.sopclassuid; dicom_all.sourceimagesequence; dicom_all.studyinstanceuid,9,2100,True,ok,False,sf_bq345 sf_bq346,IDC,snowflake,"In publicly accessible DICOM data where the Modality is 'SEG' and the SOPClassUID is '1.2.840.10008.5.1.4.1.1.66.4', and each segmentation references its original SOPInstanceUID, which five segmentation categories (by 'SegmentedPropertyCategory.CodeMeaning') occur most frequently?","WITH segs AS ( SELECT d.""SOPInstanceUID"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" d WHERE d.""access"" = 'Public' AND d.""Modality"" = 'SEG' AND d.""SOPClassUID"" = '1.2.840.10008.5.1.4.1.1.66.4' ), refs AS ( SELECT s.""SOPInstanceUID"" AS ""seg_sop"", d.""ReferencedSOPInstanceUID""::string AS ""ref_sop"" FROM segs s JOIN ""IDC"".""IDC_V17"".""DICOM_ALL"" d ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"" WHERE d.""ReferencedSOPInstanceUID"" IS NOT NULL UNION ALL SELECT s.""SOPInstanceUID"", f.value:""ReferencedSOPInstanceUID""::string FROM segs s JOIN ""IDC"".""IDC_V17"".""DICOM_ALL"" d ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"", LATERAL FLATTEN(INPUT => d.""SourceImageSequence"") f WHERE f.value:""ReferencedSOPInstanceUID"" IS NOT NULL UNION ALL SELECT s.""SOPInstanceUID"", f.value:""ReferencedSOPInstanceUID""::string FROM segs s JOIN ""IDC"".""IDC_V17"".""DICOM_ALL"" d ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"", LATERAL FLATTEN(INPUT => d.""ReferencedImageSequence"") f WHERE f.value:""ReferencedSOPInstanceUID"" IS NOT NULL UNION ALL SELECT s.""SOPInstanceUID"", f2.value:""ReferencedSOPInstanceUID""::string FROM segs s JOIN ""IDC"".""IDC_V17"".""DICOM_ALL"" d ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"", LATERAL FLATTEN(INPUT => d.""DerivationImageSequence"") f1, LATERAL FLATTEN(INPUT => f1.value:""SourceImageSequence"") f2 WHERE f2.value:""ReferencedSOPInstanceUID"" IS NOT NULL UNION ALL SELECT s.""SOPInstanceUID"", ri.value:""ReferencedSOPInstanceUID""::string FROM segs s JOIN ""IDC"".""IDC_V17"".""DICOM_ALL"" d ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"", LATERAL FLATTEN(INPUT => d.""ReferencedSeriesSequence"") rs, LATERAL FLATTEN(INPUT => rs.value:""ReferencedInstanceSequence"") ri WHERE ri.value:""ReferencedSOPInstanceUID"" IS NOT NULL UNION ALL SELECT s.""SOPInstanceUID"", ri.value:""ReferencedSOPInstanceUID""::string FROM segs s JOIN ""IDC"".""IDC_V17"".""DICOM_ALL"" d ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"", LATERAL FLATTEN(INPUT => d.""ReferencedImageEvidenceSequence"") rie, LATERAL FLATTEN(INPUT => rie.value:""ReferencedSeriesSequence"") rs, LATERAL FLATTEN(INPUT => rs.value:""ReferencedInstanceSequence"") ri WHERE ri.value:""ReferencedSOPInstanceUID"" IS NOT NULL ), seg_with_ref AS ( SELECT DISTINCT ""seg_sop"" FROM refs ) SELECT seg.""SegmentedPropertyCategory"":""CodeMeaning""::string AS ""SegmentedPropertyCategory_CodeMeaning"", COUNT(*) AS ""count"" FROM ""IDC"".""IDC_V17"".""SEGMENTATIONS"" AS seg JOIN seg_with_ref r ON seg.""SOPInstanceUID"" = r.""seg_sop"" GROUP BY 1 ORDER BY 2 DESC LIMIT 5",snow,sf_bq346,dicom_all.access; dicom_all.derivationimagesequence; dicom_all.modality; dicom_all.referencedimageevidencesequence; dicom_all.referencedimagesequence; dicom_all.referencedseriessequence; dicom_all.referencedsopinstanceuid; dicom_all.sopclassuid; dicom_all.sopinstanceuid; dicom_all.sourceimagesequence; segmentations.segmentedpropertycategory; segmentations.sopinstanceuid,12,2100,True,ok,False,sf_bq346 sf_bq347,IDC,snowflake,"From the union of the specified MR series with SeriesInstanceUID 1.3.6.1.4.1.14519.5.2.1.3671.4754.105976129314091491952445656147 and all associated segmentation instances, which modality has the greatest number of SOP instances in total, and how many are there?","WITH ""TARGET_SERIES"" AS ( SELECT '1.3.6.1.4.1.14519.5.2.1.3671.4754.105976129314091491952445656147' AS ""SeriesInstanceUID"" UNION SELECT DISTINCT ""SeriesInstanceUID"" FROM ""IDC"".""IDC_V17"".""SEGMENTATIONS"" WHERE ""segmented_SeriesInstanceUID"" = '1.3.6.1.4.1.14519.5.2.1.3671.4754.105976129314091491952445656147' ), ""COUNTS"" AS ( SELECT ""Modality"", COUNT(*) AS ""SOP_Instance_Count"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" WHERE ""SeriesInstanceUID"" IN ( SELECT ""SeriesInstanceUID"" FROM ""TARGET_SERIES"" ) GROUP BY ""Modality"" ) SELECT ""Modality"", ""SOP_Instance_Count"" FROM ""COUNTS"" QUALIFY ROW_NUMBER() OVER (ORDER BY ""SOP_Instance_Count"" DESC, ""Modality"") = 1",snow,sf_bq347,dicom_all.modality; dicom_all.seriesinstanceuid; segmentations.segmented_seriesinstanceuid; segmentations.seriesinstanceuid,4,2100,True,ok,False,sf_bq347 sf_bq349,GEO_OPENSTREETMAP,snowflake,"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?","WITH admin_candidates AS ( SELECT pf.""osm_id"", pf.""geometry"", pf.""osm_timestamp"" FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_FEATURES AS pf, LATERAL FLATTEN(INPUT => pf.""all_tags"") tag WHERE pf.""feature_type"" = 'multipolygons' AND tag.value:""key""::STRING = 'boundary' AND LOWER(TRIM(tag.value:""value""::STRING)) = 'administrative' AND pf.""osm_id"" IS NOT NULL AND pf.""geometry"" IS NOT NULL ), admin_polygons AS ( SELECT ""osm_id"", ""geometry"" FROM ( SELECT ac.*, ROW_NUMBER() OVER (PARTITION BY ac.""osm_id"" ORDER BY ac.""osm_timestamp"" DESC NULLS LAST, ac.""osm_id"" ASC) AS rn FROM admin_candidates ac ) WHERE rn = 1 ), polygons_geog AS ( SELECT ""osm_id"", ST_GEOGRAPHYFROMWKB(""geometry"") AS ""geom"" FROM admin_polygons ), amenity_nodes AS ( SELECT DISTINCT pn.""id"" AS ""node_id"", pn.""latitude"" AS ""latitude"", pn.""longitude"" AS ""longitude"" FROM GEO_OPENSTREETMAP.GEO_OPENSTREETMAP.PLANET_NODES AS pn, LATERAL FLATTEN(INPUT => pn.""all_tags"") tag WHERE tag.value:""key""::STRING = 'amenity' AND pn.""latitude"" IS NOT NULL AND pn.""longitude"" IS NOT NULL ), nodes_geog AS ( SELECT ""node_id"", ST_MAKEPOINT(""longitude"", ""latitude"") AS ""pt"" FROM amenity_nodes ), counts_per_polygon AS ( SELECT p.""osm_id"" AS ""osm_id"", COALESCE(COUNT(DISTINCT n.""node_id""), 0) AS ""cnt"" FROM polygons_geog p LEFT JOIN nodes_geog n ON ST_DWITHIN(p.""geom"", n.""pt"", 0.0) GROUP BY p.""osm_id"" ), median_val AS ( SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ""cnt"") AS ""median_cnt"" FROM counts_per_polygon ), distances AS ( SELECT c.""osm_id"", c.""cnt"", ABS(c.""cnt"" - m.""median_cnt"") AS ""dist"" FROM counts_per_polygon c CROSS JOIN median_val m ) SELECT ""osm_id"" FROM distances ORDER BY ""dist"" ASC NULLS LAST, ""osm_id"" ASC LIMIT 1;",snow,sf_bq349,planet_features.all_tags; planet_features.feature_type; planet_features.geometry; planet_features.osm_id; planet_features.osm_timestamp; planet_nodes.all_tags; planet_nodes.id; planet_nodes.latitude; planet_nodes.longitude,9,86,True,fix,True,sf_bq349 sf_bq350,OPEN_TARGETS_PLATFORM_1,bigquery,"For the detailed molecule data, Please display the drug id, drug type and withdrawal status for approved drugs with a black box warning and known drug type among 'Keytruda', 'Vioxx', 'Premarin', and 'Humira'","DECLARE my_drug_list ARRAY; SET my_drug_list = [ 'Keytruda', 'Vioxx', 'Humira', 'Premarin' ]; SELECT id AS drug_id, tradeNameList.element AS drug_trade_name, drugType AS drug_type, hasBeenWithdrawn AS drug_withdrawn FROM `open-targets-prod.platform.molecule`, UNNEST (tradeNames.list) AS tradeNameList WHERE tradeNameList.element IN UNNEST(my_drug_list) AND isApproved = TRUE AND blackBoxWarning = TRUE AND drugType != 'Unknown'; ",lite,bq350,molecule.blackboxwarning; molecule.drugtype; molecule.hasbeenwithdrawn; molecule.id; molecule.isapproved; molecule.tradenames,6,332,True,ok,False,bq350 sf_bq352,SDOH,bigquery,Please list the average number of prenatal weeks in 2018 for counties in Wisconsin where more than 5% of the employed population had commutes of 45-59 minutes in 2017.,"WITH natality_2018 AS ( SELECT County_of_Residence_FIPS AS FIPS, Ave_Number_of_Prenatal_Wks AS Vist_Ave, County_of_Residence FROM `bigquery-public-data.sdoh_cdc_wonder_natality.county_natality` WHERE SUBSTR(County_of_Residence_FIPS, 0, 2) = ""55"" AND Year = '2018-01-01' ), acs_2017 AS ( SELECT geo_id, commute_45_59_mins, employed_pop FROM `bigquery-public-data.census_bureau_acs.county_2017_5yr` ), corr_tbl AS ( SELECT n.County_of_Residence, ROUND((a.commute_45_59_mins / a.employed_pop) * 100, 2) AS percent_high_travel, n.Vist_Ave FROM acs_2017 a JOIN natality_2018 n ON a.geo_id = n.FIPS ) SELECT County_of_Residence, Vist_Ave FROM corr_tbl WHERE percent_high_travel > 5 ",lite,bq352,county_*.ave_number_of_prenatal_wks; county_*.commute_45_59_mins; county_*.county_of_residence; county_*.county_of_residence_fips; county_*.employed_pop; county_*.geo_id; county_*.year,7,4008,True,ok,False,bq352 sf_bq354,CMS_DATA,bigquery,"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.","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",lite,bq354,concept.concept_code; concept.concept_id; concept.standard_concept; concept.vocabulary_id; concept_ancestor.ancestor_concept_id; concept_ancestor.descendant_concept_id; concept_relationship.concept_id_1; concept_relationship.concept_id_2; concept_relationship.relationship_id; condition_occurrence.condition_concept_id; condition_occurrence.person_id; person.person_id,12,694,True,ok,False,bq354 sf_bq355,CMS_DATA,bigquery,Please tell me the percentage of participants not using quinapril and related medications(Quinapril RxCUI: 35208).,"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",lite,bq355,concept.concept_code; concept.concept_id; concept.vocabulary_id; concept_ancestor.ancestor_concept_id; concept_ancestor.descendant_concept_id; drug_exposure.drug_concept_id; drug_exposure.person_id; person.person_id,8,694,True,ok,False,bq355 sf_bq357,NOAA_DATA,bigquery,"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"".","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",lite,bq357,icoads_core_*.day; icoads_core_*.latitude; icoads_core_*.longitude; icoads_core_*.month; icoads_core_*.wind_speed; icoads_core_*.year,6,745,True,ok,False,bq357 sf_bq358,NEW_YORK_CITIBIKE_1,snowflake,"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.","WITH weather_check AS ( SELECT ""temp"" FROM NEW_YORK_CITIBIKE_1.NOAA_GSOD.GSOD2015 WHERE ""wban"" = '94728' AND ""mo"" = '07' AND ""da"" = '15' ), nyc_zips AS ( SELECT ""zip_code"", TO_GEOGRAPHY(""zip_code_geom"") AS geom FROM NEW_YORK_CITIBIKE_1.GEO_US_BOUNDARIES.ZIP_CODES WHERE ""state_code"" = 'NY' AND ""city"" ILIKE '%New York%' ), jul15_trips AS ( SELECT t.""bikeid"", ST_POINT(t.""start_station_longitude"", t.""start_station_latitude"") AS start_pt, ST_POINT(t.""end_station_longitude"", t.""end_station_latitude"") AS end_pt FROM NEW_YORK_CITIBIKE_1.NEW_YORK_CITIBIKE.CITIBIKE_TRIPS t CROSS JOIN weather_check w WHERE TO_TIMESTAMP(t.""starttime"" / 1000000)::DATE = '2015-07-15' ) SELECT sz.""zip_code"" AS start_zip, ez.""zip_code"" AS end_zip FROM jul15_trips jt JOIN nyc_zips sz ON ST_CONTAINS(sz.geom, jt.start_pt) JOIN nyc_zips ez ON ST_CONTAINS(ez.geom, jt.end_pt) ORDER BY start_zip ASC, end_zip DESC LIMIT 1;",snow,sf_bq358,citibike_trips.bikeid; citibike_trips.end_station_latitude; citibike_trips.end_station_longitude; citibike_trips.start_station_latitude; citibike_trips.start_station_longitude; citibike_trips.starttime; gsod_*.da; gsod_*.mo; gsod_*.temp; gsod_*.wban; zip_codes.city; zip_codes.state_code; zip_codes.zip_code; zip_codes.zip_code_geom,14,245,True,ok,False,sf_bq358 sf_bq359,GITHUB_REPOS,snowflake,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.,"WITH js_flattened AS ( SELECT ""repo_name"", f.value:""name""::STRING AS ""lang"", TRY_CAST(f.value:""bytes""::STRING AS NUMBER) AS ""bytes"" FROM GITHUB_REPOS.GITHUB_REPOS.LANGUAGES, LATERAL FLATTEN(INPUT => ""language"") f ), primary_lang AS ( SELECT ""repo_name"", ""lang"", ""bytes"", ROW_NUMBER() OVER ( PARTITION BY ""repo_name"" ORDER BY ""bytes"" DESC NULLS LAST, ""lang"" ASC ) AS ""rn"" FROM js_flattened ), js_primary_repos AS ( SELECT ""repo_name"" FROM primary_lang WHERE ""rn"" = 1 AND LOWER(""lang"") = 'javascript' ), commits_agg AS ( SELECT ""repo_name"", COUNT(DISTINCT ""commit"") AS ""commit_count"" FROM GITHUB_REPOS.GITHUB_REPOS.SAMPLE_COMMITS WHERE ""repo_name"" IS NOT NULL GROUP BY ""repo_name"" ) SELECT j.""repo_name"" AS ""repo_name"", c.""commit_count"" AS ""commit_count"" FROM js_primary_repos j JOIN commits_agg c ON j.""repo_name"" = c.""repo_name"" ORDER BY c.""commit_count"" DESC NULLS LAST, j.""repo_name"" ASC LIMIT 2;",snow,sf_bq359,languages.language; languages.repo_name; sample_commits.commit; sample_commits.repo_name,4,34,True,ok,False,sf_bq359 sf_bq360,NPPES,bigquery,"Among healthcare providers whose practice location is in Mountain View, CA, and who have a specified specialization in the field healthcare provider taxonomy, identify the top 10 most common specializations based on the count of distinct NPIs. Then determine which of those top 10 has a count of distinct NPIs closest to the average count across those 10 specializations.","WITH specialist_counts AS ( SELECT healthcare_provider_taxonomy_1_specialization, COUNT(DISTINCT npi) AS number_specialist FROM `bigquery-public-data.nppes.npi_optimized` WHERE provider_business_practice_location_address_city_name = ""MOUNTAIN VIEW"" AND provider_business_practice_location_address_state_name = ""CA"" AND healthcare_provider_taxonomy_1_specialization > """" GROUP BY healthcare_provider_taxonomy_1_specialization ), top_10_specialists AS ( SELECT healthcare_provider_taxonomy_1_specialization, number_specialist FROM specialist_counts ORDER BY number_specialist DESC LIMIT 10 ), average_value AS ( SELECT AVG(number_specialist) AS average_specialist FROM top_10_specialists ), closest_to_average AS ( SELECT healthcare_provider_taxonomy_1_specialization, number_specialist, ABS(number_specialist - (SELECT average_specialist FROM average_value)) AS difference FROM top_10_specialists ) SELECT healthcare_provider_taxonomy_1_specialization FROM closest_to_average ORDER BY difference LIMIT 1;",lite,bq360,npi_optimized.healthcare_provider_taxonomy_1_specialization; npi_optimized.npi; npi_optimized.provider_business_practice_location_address_city_name; npi_optimized.provider_business_practice_location_address_state_name,4,816,True,ok,False,bq360 sf_bq362,CHICAGO,bigquery,Which three companies had the largest increase in trip numbers between two consecutive months in 2018?,"select company from (select *, row_number() over(partition by company order by month_o_month_calc desc) as rownum from (select *, num_trips - lag(num_trips) over(partition by company order by month) as month_o_month_calc from (SELECT company, format_date(""%Y-%m"", date_sub((cast(trip_start_timestamp as date)), interval 1 month)) as prev_month, format_date(""%Y-%m"", cast(trip_start_timestamp as date)) AS month, count(1) AS num_trips from `bigquery-public-data.chicago_taxi_trips.taxi_trips` where extract(YEAR from trip_start_timestamp) = 2018 group by company, month, prev_month order by company,month) order by company, month_o_month_calc desc) ) where rownum = 1 order by month_o_month_calc desc, company limit 3",lite,bq362,taxi_trips.company; taxi_trips.trip_start_timestamp,2,45,True,ok,False,bq362 sf_bq363,CHICAGO,bigquery,"Calculate the total number of trips and average fare (formatted to two decimal places) for ten equal-sized quantile groups. Create ten quantile groups by partitioning the trip duration dimension (from 1-50 minutes) into equal sets. Each group should represent a similar number of distinct minute values. Display each group's time range formatted as ""XXm to XXm"" (where the numbers are zero-padded to two digits), the total trips count, and the average fare. The time ranges should represent the minimum and maximum duration values within each quantile. Sort the results chronologically by time range. Use NTILE(10) to create the quantiles from the ordered trip durations.","SELECT FORMAT('%02.0fm to %02.0fm', min_minutes, max_minutes) AS minutes_range, SUM(trips) AS total_trips, FORMAT('%3.2f', SUM(total_fare) / SUM(trips)) AS average_fare FROM ( SELECT MIN(duration_in_minutes) OVER (quantiles) AS min_minutes, MAX(duration_in_minutes) OVER (quantiles) AS max_minutes, SUM(trips) AS trips, SUM(total_fare) AS total_fare FROM ( SELECT ROUND(trip_seconds / 60) AS duration_in_minutes, NTILE(10) OVER (ORDER BY trip_seconds / 60) AS quantile, COUNT(1) AS trips, SUM(fare) AS total_fare FROM `bigquery-public-data.chicago_taxi_trips.taxi_trips` WHERE ROUND(trip_seconds / 60) BETWEEN 1 AND 50 GROUP BY trip_seconds, duration_in_minutes ) GROUP BY duration_in_minutes, quantile WINDOW quantiles AS (PARTITION BY quantile) ) GROUP BY minutes_range ORDER BY Minutes_range",lite,bq363,taxi_trips.fare; taxi_trips.trip_seconds,2,45,True,ok,False,bq363 sf_bq366,THE_MET,bigquery,"What are the top three most frequently associated labels with artworks from each historical period in The Met's collection, only considering labels linked to 500 or more artworks? Provide me with the period, label, and the associated count.","SELECT period, description, c FROM ( SELECT a.period, b.description, count(*) c, row_number() over (partition by period order by count(*) desc) seqnum FROM `bigquery-public-data.the_met.objects` a JOIN ( SELECT label.description as description, object_id FROM `bigquery-public-data.the_met.vision_api_data`, UNNEST(labelAnnotations) label ) b ON a.object_id = b.object_id WHERE a.period is not null group by 1,2 ) WHERE seqnum <= 3 AND c >= 500 # only include labels that have 50 or more pieces associated with it ORDER BY period, c desc;",lite,bq366,objects.object_id; objects.period; vision_api_data.labelannotations; vision_api_data.object_id,4,61,True,ok,False,bq366 sf_bq374,GA360,bigquery,"Calculates the percentage of new users who, between August 1, 2016, and April 30, 2017, both stayed on the site for more than 5 minutes during their initial visit and made a purchase on a subsequent visit at any later time, relative to the total number of new users in the same period.","WITH initial_visits AS ( SELECT fullVisitorId, MIN(visitStartTime) AS initialVisitStartTime FROM `bigquery-public-data.google_analytics_sample.*` WHERE totals.newVisits = 1 AND date BETWEEN '20160801' AND '20170430' GROUP BY fullVisitorId ), qualified_initial_visits AS ( SELECT s.fullVisitorId, s.visitStartTime AS initialVisitStartTime, s.totals.timeOnSite AS time_on_site FROM `bigquery-public-data.google_analytics_sample.*` s JOIN initial_visits i ON s.fullVisitorId = i.fullVisitorId AND s.visitStartTime = i.initialVisitStartTime WHERE s.totals.timeOnSite > 300 ), filtered_data AS ( SELECT q.fullVisitorId, q.time_on_site, IF(COUNTIF(s.visitStartTime > q.initialVisitStartTime AND s.totals.transactions > 0) > 0, 1, 0) AS will_buy_on_return_visit FROM qualified_initial_visits q LEFT JOIN `bigquery-public-data.google_analytics_sample.*` s ON q.fullVisitorId = s.fullVisitorId GROUP BY q.fullVisitorId, q.time_on_site ), matching_users AS ( SELECT fullVisitorId FROM filtered_data WHERE time_on_site > 300 AND will_buy_on_return_visit = 1 ), total_new_users AS ( SELECT COUNT(DISTINCT fullVisitorId) AS total_new_users FROM `bigquery-public-data.google_analytics_sample.*` WHERE totals.newVisits = 1 AND date BETWEEN '20160801' AND '20170430' ), final_counts AS ( SELECT COUNT(DISTINCT fullVisitorId) AS users_matching_criteria FROM matching_users ) SELECT (final_counts.users_matching_criteria / total_new_users.total_new_users) * 100 AS percentage_matching_criteria FROM final_counts, total_new_users; ",lite,bq374,ga_sessions_*.date; ga_sessions_*.fullvisitorid; ga_sessions_*.totals; ga_sessions_*.visitstarttime,4,16,True,ok,False,bq374 sf_bq376,SAN_FRANCISCO_PLUS,bigquery,"For each neighborhood in San Francisco where at least one bike share station and at least one crime incident are located, provide the neighborhood name along with the total count of bike share stations and the total number of crime incidents in that neighborhood.","WITH station_neighborhoods AS ( SELECT bs.station_id, bs.name AS station_name, nb.neighborhood FROM `bigquery-public-data.san_francisco.bikeshare_stations` bs JOIN bigquery-public-data.san_francisco_neighborhoods.boundaries nb ON ST_Intersects(ST_GeogPoint(bs.longitude, bs.latitude), nb.neighborhood_geom) ), neighborhood_crime_counts AS ( SELECT neighborhood, COUNT(*) AS crime_count FROM ( SELECT n.neighborhood FROM bigquery-public-data.san_francisco.sfpd_incidents i JOIN bigquery-public-data.san_francisco_neighborhoods.boundaries n ON ST_Intersects(ST_GeogPoint(i.longitude, i.latitude), n.neighborhood_geom) ) AS incident_neighborhoods GROUP BY neighborhood ) SELECT sn.neighborhood, COUNT(station_name) AS station_number, ANY_VALUE(ncc.crime_count) AS crime_number FROM station_neighborhoods sn JOIN neighborhood_crime_counts ncc ON sn.neighborhood = ncc.neighborhood GROUP BY sn.neighborhood ORDER BY crime_number ASC ",lite,bq376,boundaries.neighborhood; boundaries.neighborhood_geom; sfpd_incidents.latitude; sfpd_incidents.longitude,4,556,True,ok,False,bq376 sf_bq377,GITHUB_REPOS,snowflake,Extract and count the frequency of all package names listed in the require section of JSON-formatted content,"WITH json_content AS ( SELECT ""content"", ""sample_ref"", ""sample_path"" FROM ""GITHUB_REPOS"".""GITHUB_REPOS"".""SAMPLE_CONTENTS"" WHERE ""sample_path"" ILIKE '%.json' AND ""content"" IS NOT NULL AND ""content"" != '' ), parsed_json AS ( SELECT ""sample_ref"", ""sample_path"", TRY_PARSE_JSON(""content"") AS ""parsed_content"" FROM json_content WHERE TRY_PARSE_JSON(""content"") IS NOT NULL ), require_sections AS ( SELECT ""sample_ref"", ""sample_path"", ""parsed_content"":""require"" AS ""require_obj"" FROM parsed_json WHERE ""parsed_content"":""require"" IS NOT NULL ), flattened_packages AS ( SELECT r.""sample_ref"", r.""sample_path"", f.key::STRING AS ""package_name"" FROM require_sections r, LATERAL FLATTEN(input => r.""require_obj"") f ) SELECT ""package_name"", COUNT(*) AS ""frequency"" FROM flattened_packages WHERE ""package_name"" IS NOT NULL GROUP BY ""package_name"" ORDER BY ""frequency"" DESC, ""package_name""",snow,sf_bq377,sample_contents.content; sample_contents.sample_path; sample_contents.sample_ref,3,34,True,ok,False,sf_bq377 sf_bq379,OPEN_TARGETS_PLATFORM_1,bigquery,Which target approved symbol has the overall association score closest to the mean score for psoriasis?,"WITH AvgScore AS ( SELECT AVG(associations.score) AS avg_score FROM `open-targets-prod.platform.associationByOverallDirect` AS associations JOIN `open-targets-prod.platform.diseases` AS diseases ON associations.diseaseId = diseases.id WHERE diseases.name = 'psoriasis' ) SELECT targets.approvedSymbol AS target_approved_symbol FROM `open-targets-prod.platform.associationByOverallDirect` AS associations JOIN `open-targets-prod.platform.diseases` AS diseases ON associations.diseaseId = diseases.id JOIN `open-targets-prod.platform.targets` AS targets ON associations.targetId = targets.id CROSS JOIN AvgScore WHERE diseases.name = 'psoriasis' ORDER BY ABS(associations.score - AvgScore.avg_score) ASC LIMIT 1 ",lite,bq379,associationbyoveralldirect.diseaseid; associationbyoveralldirect.score; associationbyoveralldirect.targetid; diseases.id; diseases.name; targets.approvedsymbol; targets.id,7,332,True,ok,False,bq379 sf_bq383,GHCN_D,bigquery,"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)","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; ",lite,bq383,ghcnd_*.date; ghcnd_*.element; ghcnd_*.id; ghcnd_*.qflag; ghcnd_*.value,5,31,True,ok,False,bq383 sf_bq389,EPA_HISTORICAL_AIR_QUALITY,bigquery,"Please calculate the monthly average levels of PM10, PM2.5 FRM, PM2.5 non-FRM, volatile organic emissions, SO2 (scaled by a factor of 10), and Lead (scaled by a factor of 100) air pollutants in California for the year 2020.","SELECT pm10.month AS month, pm10.avg AS pm10, pm25_frm.avg AS pm25_frm, pm25_nonfrm.avg AS pm25_nonfrm, co.avg AS co, so2.avg AS so2, lead.avg AS lead FROM (SELECT AVG(arithmetic_mean) AS avg, EXTRACT(YEAR FROM date_local) AS year, EXTRACT(MONTH FROM date_local) AS month FROM `bigquery-public-data.epa_historical_air_quality.pm10_daily_summary` WHERE state_name = 'California' AND EXTRACT(YEAR FROM date_local) = 2020 GROUP BY year, month) AS pm10 JOIN (SELECT AVG(arithmetic_mean) AS avg, EXTRACT(YEAR FROM date_local) AS year, EXTRACT(MONTH FROM date_local) AS month FROM `bigquery-public-data.epa_historical_air_quality.pm25_frm_daily_summary` WHERE state_name = 'California' AND EXTRACT(YEAR FROM date_local) = 2020 GROUP BY year, month) AS pm25_frm ON pm10.year = pm25_frm.year AND pm10.month = pm25_frm.month JOIN (SELECT AVG(arithmetic_mean) AS avg, EXTRACT(YEAR FROM date_local) AS year, EXTRACT(MONTH FROM date_local) AS month FROM `bigquery-public-data.epa_historical_air_quality.pm25_nonfrm_daily_summary` WHERE state_name = 'California' AND EXTRACT(YEAR FROM date_local) = 2020 GROUP BY year, month) AS pm25_nonfrm ON pm10.year = pm25_nonfrm.year AND pm10.month = pm25_nonfrm.month JOIN (SELECT AVG(arithmetic_mean) * 100 AS avg, EXTRACT(YEAR FROM date_local) AS year, EXTRACT(MONTH FROM date_local) AS month FROM `bigquery-public-data.epa_historical_air_quality.lead_daily_summary` WHERE state_name = 'California' AND EXTRACT(YEAR FROM date_local) = 2020 GROUP BY year, month) AS lead ON pm10.year = lead.year AND pm10.month = lead.month JOIN (SELECT AVG(arithmetic_mean) AS avg, EXTRACT(YEAR FROM date_local) AS year, EXTRACT(MONTH FROM date_local) AS month FROM `bigquery-public-data.epa_historical_air_quality.voc_daily_summary` WHERE state_name = 'California' AND EXTRACT(YEAR FROM date_local) = 2020 GROUP BY year, month) AS co ON pm10.year = co.year AND pm10.month = co.month JOIN (SELECT AVG(arithmetic_mean) * 10 AS avg, EXTRACT(YEAR FROM date_local) AS year, EXTRACT(MONTH FROM date_local) AS month FROM `bigquery-public-data.epa_historical_air_quality.so2_daily_summary` WHERE state_name = 'California' AND EXTRACT(YEAR FROM date_local) = 2020 GROUP BY year, month) AS so2 ON pm10.year = so2.year AND pm10.month = so2.month ORDER BY month;",lite,bq389,lead_daily_summary.arithmetic_mean; lead_daily_summary.date_local; lead_daily_summary.state_name; pm10_daily_summary.arithmetic_mean; pm10_daily_summary.date_local; pm10_daily_summary.state_name; so2_daily_summary.arithmetic_mean; so2_daily_summary.date_local; so2_daily_summary.state_name; voc_daily_summary.arithmetic_mean; voc_daily_summary.date_local; voc_daily_summary.state_name,12,879,True,ok,False,bq389 sf_bq390,IDC,snowflake,"In the ""qin_prostate_repeatability"" collection, please provide the distinct StudyInstanceUIDs for studies that include T2-weighted axial MR imaging and also contain anatomical structure segmentations labeled as ""Peripheral zone.""","SELECT DISTINCT T1.""StudyInstanceUID"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" AS T1 INNER JOIN ""IDC"".""IDC_V17"".""SEGMENTATIONS"" AS T2 ON T1.""StudyInstanceUID"" = T2.""StudyInstanceUID"" WHERE T1.""collection_id"" = 'qin_prostate_repeatability' AND T1.""SeriesDescription"" = 'T2 Weighted Axial' AND T2.""SegmentedPropertyType"":CodeMeaning::STRING = 'Peripheral zone of the prostate'",snow,sf_bq390,dicom_all.collection_id; dicom_all.seriesdescription; dicom_all.studyinstanceuid; segmentations.segmentedpropertytype; segmentations.studyinstanceuid,5,2100,True,ok,False,sf_bq390 sf_bq392,NOAA_GSOD,bigquery,"What are the top 3 dates in October 2009 with the highest average temperature for station number 723758, in the format YYYY-MM-DD?","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;",lite,bq392,gsod_*.da; gsod_*.mo; gsod_*.stn; gsod_*.temp; gsod_*.year,5,44,True,ok,False,bq392 sf_bq394,NOAA_DATA,bigquery,"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.","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;",lite,bq394,icoads_core_*.air_temperature; icoads_core_*.day; icoads_core_*.dewpoint_temperature; icoads_core_*.month; icoads_core_*.sea_surface_temp; icoads_core_*.wetbulb_temperature; icoads_core_*.year,7,745,True,ok,False,bq394 sf_bq395,SDOH,bigquery,"Calculate the percentage change in the total number of unsheltered homeless people from 2015 to 2018 for each state by summing the counts over all Continuums of Care (CoCs) within each state. Then, determine the national average of these state percentage changes. Identify the five states whose percentage change is closest to this national average percentage change. Please provide the state abbreviations.","WITH homeless_2015 AS ( SELECT Unsheltered_Homeless AS U15, SUBSTR(CoC_Number, 0, 2) as State_Abbr FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc` WHERE Count_Year = 2015 ), homeless_2018 AS ( SELECT Unsheltered_Homeless AS U18, SUBSTR(CoC_Number, 0, 2) as State_Abbr FROM `bigquery-public-data.sdoh_hud_pit_homelessness.hud_pit_by_coc` WHERE Count_Year = 2018 ), unsheltered_change AS ( SELECT homeless_2018.State_Abbr, SUM(U15) AS Unsheltered_2015, SUM(U18) AS Unsheltered_2018, (SUM(U18) - SUM(U15)) / SUM(U15) * 100 AS Percent_Change FROM homeless_2018 JOIN homeless_2015 ON homeless_2018.State_Abbr = homeless_2015.State_Abbr GROUP BY State_Abbr ), average_change AS ( SELECT AVG(Percent_Change) AS Avg_Change FROM unsheltered_change ), closest_to_avg AS ( SELECT State_Abbr FROM unsheltered_change, average_change ORDER BY ABS(Percent_Change - Avg_Change) LIMIT 5 ) SELECT State_Abbr FROM closest_to_avg;",lite,bq395,hud_pit_by_coc.coc_number; hud_pit_by_coc.count_year; hud_pit_by_coc.unsheltered_homeless,3,4008,True,ok,False,bq395 sf_bq396,NHTSA_TRAFFIC_FATALITIES,bigquery,Which top 3 states had the largest differences in the number of traffic accidents between rainy and clear weather during weekends in 2016? Please also provide the respective differences for each state.,"WITH weekend_accidents AS ( SELECT state_name, CASE WHEN atmospheric_conditions_1_name = 'Rain' THEN 'Rain' WHEN atmospheric_conditions_1_name = 'Clear' THEN 'Clear' ELSE 'Other' END AS Weather_Condition, COUNT(DISTINCT consecutive_number) AS num_accidents FROM `bigquery-public-data.nhtsa_traffic_fatalities.accident_2016` WHERE EXTRACT(DAYOFWEEK FROM timestamp_of_crash) IN (1, 7) -- 1 = Sunday, 7 = Saturday AND atmospheric_conditions_1_name IN ('Rain', 'Clear') GROUP BY state_name, Weather_Condition ), weather_difference AS ( SELECT state_name, MAX(CASE WHEN Weather_Condition = 'Rain' THEN num_accidents ELSE 0 END) AS Rain_Accidents, MAX(CASE WHEN Weather_Condition = 'Clear' THEN num_accidents ELSE 0 END) AS Clear_Accidents, ABS(MAX(CASE WHEN Weather_Condition = 'Rain' THEN num_accidents ELSE 0 END) - MAX(CASE WHEN Weather_Condition = 'Clear' THEN num_accidents ELSE 0 END)) AS Difference FROM weekend_accidents GROUP BY state_name ) SELECT state_name, Difference FROM weather_difference ORDER BY Difference DESC LIMIT 3;",lite,bq396,accident_*.atmospheric_conditions_1_name; accident_*.consecutive_number; accident_*.state_name; accident_*.timestamp_of_crash,4,686,True,ok,False,bq396 sf_bq397,ECOMMERCE,bigquery,"After removing any duplicate records from the rev_transactions dataset, identify each channel grouping that has transactions from more than one country. For each such channel grouping, find the country with the highest total number of transactions and report both the country name and the sum of transactions for that channel grouping.","WITH tmp AS ( SELECT DISTINCT * FROM `data-to-insights.ecommerce.rev_transactions` -- Removing duplicated values ), tmp1 AS ( SELECT tmp.channelGrouping, tmp.geoNetwork_country, SUM(tmp.totals_transactions) AS tt FROM tmp GROUP BY 1, 2 ), tmp2 AS ( SELECT channelGrouping, geoNetwork_country, SUM(tt) AS TotalTransaction, COUNT(DISTINCT geoNetwork_country) OVER (PARTITION BY channelGrouping) AS CountryCount FROM tmp1 GROUP BY channelGrouping, geoNetwork_country ), tmp3 AS ( SELECT channelGrouping, geoNetwork_country AS Country, TotalTransaction, RANK() OVER (PARTITION BY channelGrouping ORDER BY TotalTransaction DESC) AS rnk FROM tmp2 WHERE CountryCount > 1 ) SELECT channelGrouping, Country, TotalTransaction FROM tmp3 WHERE rnk = 1;",lite,bq397,rev_transactions.channelgrouping; rev_transactions.geonetwork_country; rev_transactions.totals_transactions,3,122,True,fix,False,bq397 sf_bq398,WORLD_BANK,bigquery,What are the top three debt indicators for Russia based on the highest debt values?,"WITH russia_Data as ( SELECT distinct id.country_name, id.value, --format in DataStudio id.indicator_name FROM ( SELECT country_code, region FROM bigquery-public-data.world_bank_intl_debt.country_summary WHERE region != """" ) cs --aggregated countries do not have a region INNER JOIN ( SELECT country_code, country_name, value, indicator_name FROM bigquery-public-data.world_bank_intl_debt.international_debt WHERE true and country_code = 'RUS' ) id ON cs.country_code = id.country_code WHERE value is not null ORDER BY id.value DESC ) SELECT indicator_name FROM russia_data LIMIT 3;",lite,bq398,country_summary.country_code; country_summary.region; international_*.country_code; international_*.country_name; international_*.indicator_name; international_*.value,6,144,True,ok,False,bq398 sf_bq399,WORLD_BANK,bigquery,"Which high-income country had the highest average crude birth rate respectively in each region, and what are their corresponding average birth rate, during the 1980s?","WITH country_data AS ( SELECT country_code, short_name AS country, region, income_group FROM bigquery-public-data.world_bank_wdi.country_summary ) , birth_rate_data AS ( SELECT data.country_code, country_data.country, country_data.region, AVG(value) AS avg_birth_rate FROM bigquery-public-data.world_bank_wdi.indicators_data data LEFT JOIN country_data ON data.country_code = country_data.country_code WHERE indicator_code = ""SP.DYN.CBRT.IN"" -- Birth Rate AND EXTRACT(YEAR FROM PARSE_DATE('%Y', CAST(year AS STRING))) BETWEEN 1980 AND 1989 -- 1980s AND country_data.income_group = ""High income"" -- High-income group GROUP BY data.country_code, country_data.country, country_data.region ) , ranked_birth_rates AS ( SELECT region, country, avg_birth_rate, RANK() OVER(PARTITION BY region ORDER BY avg_birth_rate DESC) AS rank FROM birth_rate_data ) SELECT region, country, avg_birth_rate FROM ranked_birth_rates WHERE rank = 1 ORDER BY region;",lite,bq399,country_summary.country_code; country_summary.income_group; country_summary.region; country_summary.short_name; indicators_data.country_code; indicators_data.indicator_code; indicators_data.value; indicators_data.year,8,144,True,ok,False,bq399 sf_bq400,SAN_FRANCISCO_PLUS,bigquery,"For trips where 'Clay St & Drumm St' occurs before 'Sacramento St & Davis St' in the stop sequence (one direction only), what are the earliest departure times from 'Clay St & Drumm St' and the latest arrival times at 'Sacramento St & Davis St' in the format HH:MM:SS? Please provide the trip headsign for each route.","WITH SelectedStops AS ( SELECT stop_id, stop_name FROM `bigquery-public-data.san_francisco_transit_muni.stops` WHERE stop_name IN ('Clay St & Drumm St', 'Sacramento St & Davis St') ), FilteredStopTimes AS ( SELECT st.trip_id, st.stop_id, st.arrival_time, st.departure_time, st.stop_sequence, ss.stop_name FROM `bigquery-public-data.san_francisco_transit_muni.stop_times` st JOIN SelectedStops ss ON CAST(st.stop_id AS STRING) = ss.stop_id ) SELECT t.trip_headsign, MIN(st1.departure_time) AS start_time, MAX(st2.arrival_time) AS end_time FROM `bigquery-public-data.san_francisco_transit_muni.trips` t JOIN FilteredStopTimes st1 ON t.trip_id = CAST(st1.trip_id AS STRING) AND st1.stop_name = 'Clay St & Drumm St' JOIN FilteredStopTimes st2 ON t.trip_id = CAST(st2.trip_id AS STRING) AND st2.stop_name = 'Sacramento St & Davis St' WHERE st1.stop_sequence < st2.stop_sequence GROUP BY t.trip_headsign;",lite,bq400,stop_times.arrival_time; stop_times.departure_time; stop_times.stop_id; stop_times.stop_sequence; stop_times.trip_id; stops.stop_id; stops.stop_name; trips.trip_headsign; trips.trip_id,9,556,True,ok,False,bq400 sf_bq402,ECOMMERCE,bigquery,"Calculate the conversion rate from unique visitors to purchasers by using data exclusively from the `web_analytics` table in the `data-to-insights.ecommerce` dataset. A visitor is defined as a unique `fullVisitorId` present in the table, while a purchaser is a visitor who has at least one transaction recorded (`totals.transactions` is not null). The conversion rate is computed by dividing the number of unique purchasers by the total number of unique visitors. Additionally, calculate the average number of transactions per purchaser, considering only those visitors who have made at least one transaction.","WITH visitors AS ( SELECT COUNT(DISTINCT fullVisitorId) AS total_visitors FROM `data-to-insights.ecommerce.web_analytics` ), purchasers AS ( SELECT COUNT(DISTINCT fullVisitorId) AS total_purchasers FROM `data-to-insights.ecommerce.web_analytics` WHERE totals.transactions IS NOT NULL ), transactions AS ( SELECT COUNT(*) AS total_transactions, AVG(totals.transactions) AS avg_transactions_per_purchaser FROM `data-to-insights.ecommerce.web_analytics` WHERE totals.transactions IS NOT NULL ) SELECT p.total_purchasers / v.total_visitors AS conversion_rate, a.avg_transactions_per_purchaser AS avg_transactions_per_purchaser FROM visitors v, purchasers p, transactions a;",lite,bq402,web_analytics.fullvisitorid; web_analytics.totals,2,122,True,fix,False,bq402 sf_bq403,IRS_990,bigquery,Which three years in 2012-2017 have the smallest absolute difference between median revenue and median functional expenses for organizations filing IRS 990 forms? Please output three years and respective differences.,"WITH RankedData AS ( SELECT CONCAT(""20"", _TABLE_SUFFIX) AS year_filed, totrevenue, totfuncexpns, ROW_NUMBER() OVER (PARTITION BY CONCAT(""20"", _TABLE_SUFFIX) ORDER BY totrevenue) AS revenue_rank, ROW_NUMBER() OVER (PARTITION BY CONCAT(""20"", _TABLE_SUFFIX) ORDER BY totfuncexpns) AS expense_rank, COUNT(*) OVER (PARTITION BY CONCAT(""20"", _TABLE_SUFFIX)) AS total_count FROM `bigquery-public-data.irs_990.irs_990_20*` ), YearlyMedians AS ( SELECT year_filed, IF(MOD(total_count, 2) = 1, MAX(CASE WHEN revenue_rank = (total_count + 1) / 2 THEN totrevenue END), AVG(CASE WHEN revenue_rank IN ((total_count / 2), (total_count / 2) + 1) THEN totrevenue END) ) AS median_revenue, IF(MOD(total_count, 2) = 1, MAX(CASE WHEN expense_rank = (total_count + 1) / 2 THEN totfuncexpns END), AVG(CASE WHEN expense_rank IN ((total_count / 2), (total_count / 2) + 1) THEN totfuncexpns END) ) AS median_expense FROM RankedData GROUP BY year_filed, total_count ), DifferenceCalculations AS ( SELECT year_filed, median_revenue, median_expense, ABS(median_revenue - median_expense) AS difference FROM YearlyMedians ) SELECT year_filed, difference FROM DifferenceCalculations WHERE year_filed BETWEEN '2012' AND '2017' ORDER BY difference ASC LIMIT 3;",lite,bq403,irs_990_*.totfuncexpns; irs_990_*.totrevenue,2,747,True,fix,True,bq403 sf_bq406,GOOGLE_DEI,bigquery,"Please calculate the growth rates for Asians, Black people, Latinx people, Native Americans, White people, US women, US men, global women, and global men from 2014 to 2024 concerning the overall workforce.","CREATE TEMP FUNCTION GrowthRate(end_value FLOAT64, begin_value FLOAT64) RETURNS FLOAT64 AS ((end_value - begin_value) / begin_value); SELECT GrowthRate(SUM(IF(report_year=2024, race_asian, 0)), SUM(IF(report_year=2014, race_asian, 0))) AS race_asian_growth, GrowthRate(SUM(IF(report_year=2024, race_black, 0)), SUM(IF(report_year=2014, race_black, 0))) AS race_black_growth, GrowthRate(SUM(IF(report_year=2024, race_hispanic_latinx, 0)), SUM(IF(report_year=2014, race_hispanic_latinx, 0))) AS race_hispanic_growth, GrowthRate(SUM(IF(report_year=2024, race_native_american, 0)), SUM(IF(report_year=2014, race_native_american, 0))) AS race_native_american_growth, GrowthRate(SUM(IF(report_year=2024, race_white, 0)), SUM(IF(report_year=2014, race_white, 0))) AS race_white_growth, GrowthRate(SUM(IF(report_year=2024, gender_us_women, 0)), SUM(IF(report_year=2014, gender_us_women, 0))) AS gender_us_women_growth, GrowthRate(SUM(IF(report_year=2024, gender_us_men, 0)), SUM(IF(report_year=2014, gender_us_men, 0))) AS gender_us_men_growth, GrowthRate(SUM(IF(report_year=2024, gender_global_women, 0)), SUM(IF(report_year=2014, gender_global_women, 0))) AS gender_global_women_growth, GrowthRate(SUM(IF(report_year=2024, gender_global_men, 0)), SUM(IF(report_year=2014, gender_global_men, 0))) AS gender_global_men_growth FROM `bigquery-public-data.google_dei.dar_non_intersectional_representation` WHERE report_year IN (2014, 2024) AND workforce = 'overall';",lite,bq406,dar_non_intersectional_*.gender_global_men; dar_non_intersectional_*.gender_global_women; dar_non_intersectional_*.gender_us_men; dar_non_intersectional_*.gender_us_women; dar_non_intersectional_*.race_asian; dar_non_intersectional_*.race_black; dar_non_intersectional_*.race_hispanic_latinx; dar_non_intersectional_*.race_native_american; dar_non_intersectional_*.race_white; dar_non_intersectional_*.report_year; dar_non_intersectional_*.workforce,11,5995,True,ok,False,bq406 sf_bq407,COVID19_USA,bigquery,"Find the top three counties with populations over 50,000, using the 2020 5-year census data, that had the highest COVID-19 case fatality rates on August 27, 2020. For these counties, provide the name, state, median age, total population, number of confirmed COVID-19 cases per 100,000 people, number of deaths per 100,000 people, and the case fatality rate as a percentage","WITH population_data AS ( SELECT geo_id, median_age, total_pop FROM `bigquery-public-data.census_bureau_acs.county_2020_5yr` WHERE total_pop > 50000 ), covid_data AS ( SELECT county_fips_code, county_name, state, SUM(confirmed_cases) AS total_cases, SUM(deaths) AS total_deaths FROM `bigquery-public-data.covid19_usafacts.summary` WHERE date = '2020-08-27' GROUP BY county_fips_code, county_name, state ) SELECT covid.county_name, covid.state, pop.median_age, pop.total_pop, (covid.total_cases / pop.total_pop * 100000) AS confirmed_cases_per_100000, (covid.total_deaths / pop.total_pop * 100000) AS deaths_per_100000, (covid.total_deaths / covid.total_cases * 100) AS case_fatality_rate FROM covid_data covid JOIN population_data pop ON covid.county_fips_code = pop.geo_id ORDER BY case_fatality_rate DESC LIMIT 3;",lite,bq407,county_*.geo_id; county_*.median_age; county_*.total_pop; summary.confirmed_cases; summary.county_fips_code; summary.county_name; summary.date; summary.deaths; summary.state,9,6021,True,ok,False,bq407 sf_bq412,GOOGLE_ADS,snowflake,"Please retrieve the page URLs, first shown time, last shown time, removal reason, violation category, and the lower and upper bounds of times shown for the five most recently removed ads in the Croatia region (region code 'HR'), where the times shown availability date is null, the times shown lower bound exceeds 10,000, the times shown upper bound is below 25,000, and the ads used at least one non-unused audience selection approach among demographics, geographic location, contextual signals, customer lists, or topics of interest, ordering the resulting ads by their last shown time in descending order.","WITH parsed_regions AS (SELECT ""creative_page_url"", value:""first_shown""::STRING AS first_shown_str, value:""last_shown""::STRING AS last_shown_str, value:""times_shown_lower_bound""::NUMBER AS times_shown_lower, value:""times_shown_upper_bound""::NUMBER AS times_shown_upper, value:""region_code""::STRING AS region_code, value:""times_shown_availability_date"" AS availability_date FROM GOOGLE_ADS.GOOGLE_ADS_TRANSPARENCY_CENTER.REMOVED_CREATIVE_STATS, LATERAL FLATTEN(INPUT => PARSE_JSON(""region_stats""))), filtered_regions AS (SELECT ""creative_page_url"", TO_TIMESTAMP(first_shown_str) AS ""first_shown"", TO_TIMESTAMP(last_shown_str) AS ""last_shown"", times_shown_lower, times_shown_upper FROM parsed_regions WHERE region_code = 'HR' AND availability_date IS NULL AND times_shown_lower > 10000 AND times_shown_upper < 25000) SELECT T1.""creative_page_url"", T2.""first_shown"", T2.""last_shown"", PARSE_JSON(T1.""disapproval"")[0]:""removal_reason""::STRING AS ""removal_reason"", PARSE_JSON(T1.""disapproval"")[0]:""violation_category""::STRING AS ""violation_category"", T2.times_shown_lower, T2.times_shown_upper FROM GOOGLE_ADS.GOOGLE_ADS_TRANSPARENCY_CENTER.REMOVED_CREATIVE_STATS T1 INNER JOIN filtered_regions T2 ON T1.""creative_page_url"" = T2.""creative_page_url"" WHERE (PARSE_JSON(T1.""audience_selection_approach_info""):""demographic_info""::STRING != 'CRITERIA_UNUSED' OR PARSE_JSON(T1.""audience_selection_approach_info""):""geo_location""::STRING != 'CRITERIA_UNUSED' OR PARSE_JSON(T1.""audience_selection_approach_info""):""contextual_signals""::STRING != 'CRITERIA_UNUSED' OR PARSE_JSON(T1.""audience_selection_approach_info""):""customer_lists""::STRING != 'CRITERIA_UNUSED' OR PARSE_JSON(T1.""audience_selection_approach_info""):""topics_of_interest""::STRING != 'CRITERIA_UNUSED') ORDER BY T2.""last_shown"" DESC LIMIT 5;",snow,sf_bq412,removed_creative_stats.audience_selection_approach_info; removed_creative_stats.creative_page_url; removed_creative_stats.disapproval; removed_creative_stats.region_stats,4,16,True,ok,False,sf_bq412 sf_bq413,DIMENSIONS_AI_COVID19,bigquery,"Retrieve the venue titles of publications that have a `date_inserted` from the year 2021 onwards and are associated with a grid whose address city is 'Qianjiang'. For each publication, prioritize the venue title by selecting the journal title first if it exists; if not, then the proceedings title; if that's also unavailable, then the book title; and finally, if none of those are available, the book series title.","SELECT COALESCE(p.journal.title, p.proceedings_title.preferred, p.book_title.preferred, p.book_series_title.preferred) AS venue, FROM `bigquery-public-data.dimensions_ai_covid19.publications` p LEFT JOIN UNNEST(research_orgs) AS research_orgs_grids LEFT JOIN `bigquery-public-data.dimensions_ai_covid19.grid` grid ON grid.id=research_orgs_grids WHERE EXTRACT(YEAR FROM date_inserted) >= 2021 AND grid.address.city = 'Qianjiang'",lite,bq413,grid.address; grid.id; publications.book_series_title; publications.book_title; publications.date_inserted; publications.journal; publications.proceedings_title; publications.research_orgs,8,282,True,fix,True,bq413 sf_bq414,THE_MET,bigquery,"Retrieve the object id, title, and the formatted metadata date (as a string in 'YYYY-MM-DD' format) for objects in the ""The Libraries"" department where the cropConfidence is greater than 0.5, the object's title contains the word ""book"".","SELECT a.object_id, a.title, FORMAT_TIMESTAMP('%Y-%m-%d', a.metadata_date) AS formatted_metadata_date FROM `bigquery-public-data.the_met.objects` a JOIN ( SELECT object_id, cropHints.confidence AS cropConfidence FROM `bigquery-public-data.the_met.vision_api_data`, UNNEST(cropHintsAnnotation.cropHints) cropHints ) b ON a.object_id = b.object_id WHERE a.department = ""The Libraries"" AND b.cropConfidence > 0.5 AND a.title LIKE ""%book%""",lite,bq414,objects.department; objects.metadata_date; objects.object_id; objects.title; vision_api_data.crophintsannotation; vision_api_data.object_id,6,61,True,ok,False,bq414 sf_bq419,NOAA_DATA,bigquery,"Which 5 states had the most storm events from 1980 to 1995, considering only the top 1000 states with the highest event counts each year? Please use state abbreviations.","WITH s80 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1980` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s81 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1981` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s82 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1982` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s83 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1983` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s84 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1984` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s85 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1985` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s86 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1986` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s87 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1987` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s88 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1988` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s89 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1989` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s90 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1990` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s91 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1991` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s92 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1992` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s93 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1993` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s94 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1994` GROUP BY state ORDER BY num_events DESC LIMIT 1000), s95 as (SELECT state, COUNT(event_id) as num_events FROM `bigquery-public-data.noaa_historic_severe_storms.storms_1995` GROUP BY state ORDER BY num_events DESC LIMIT 1000) SELECT s80.state, s80.num_events + s81.num_events + s82.num_events + s83.num_events + s84.num_events + s85.num_events + s86.num_events + s87.num_events + s88.num_events + s89.num_events + s90.num_events + s91.num_events + s92.num_events + s93.num_events + s94.num_events + s95.num_events as total_events FROM s80 FULL JOIN s81 ON s80.state = s81.state FULL JOIN s82 ON s82.state = s81.state FULL JOIN s83 ON s83.state = s81.state FULL JOIN s84 ON s84.state = s81.state FULL JOIN s85 ON s85.state = s81.state FULL JOIN s86 ON s86.state = s81.state FULL JOIN s87 ON s87.state = s81.state FULL JOIN s88 ON s88.state = s81.state FULL JOIN s89 ON s89.state = s81.state FULL JOIN s90 ON s90.state = s81.state FULL JOIN s91 ON s91.state = s81.state FULL JOIN s92 ON s92.state = s81.state FULL JOIN s93 ON s93.state = s81.state FULL JOIN s94 ON s94.state = s81.state FULL JOIN s95 ON s95.state = s81.state ORDER BY total_events DESC LIMIT 5;",lite,bq419,storms_*.event_id; storms_*.state,2,745,True,ok,False,bq419 sf_bq421,IDC,snowflake,"Can you list all unique pairs of embedding medium and staining substance code meanings, along with the number of occurrences for each pair, based on distinct embedding medium and staining substance codes from the 'SM' modality in the DICOM dataset's un-nested specimen preparation sequences, ensuring that the codes are from the SCT coding scheme?","WITH SpecimenPreparationSequence_unnested AS ( SELECT d.""SOPInstanceUID"", concept_name_code_sequence.value:""CodeMeaning""::STRING AS ""cnc_cm"", concept_name_code_sequence.value:""CodingSchemeDesignator""::STRING AS ""cnc_csd"", concept_name_code_sequence.value:""CodeValue""::STRING AS ""cnc_val"", concept_code_sequence.value:""CodeMeaning""::STRING AS ""ccs_cm"", concept_code_sequence.value:""CodingSchemeDesignator""::STRING AS ""ccs_csd"", concept_code_sequence.value:""CodeValue""::STRING AS ""ccs_val"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" AS d, LATERAL FLATTEN(input => d.""SpecimenDescriptionSequence"") AS spec_desc, LATERAL FLATTEN(input => spec_desc.value:""SpecimenPreparationSequence"") AS prep_seq, LATERAL FLATTEN(input => prep_seq.value:""SpecimenPreparationStepContentItemSequence"") AS prep_step, LATERAL FLATTEN(input => prep_step.value:""ConceptNameCodeSequence"") AS concept_name_code_sequence, LATERAL FLATTEN(input => prep_step.value:""ConceptCodeSequence"") AS concept_code_sequence ), slide_embedding AS ( SELECT ""SOPInstanceUID"", ARRAY_AGG(DISTINCT(CONCAT(""ccs_cm"", ':', ""ccs_csd"", ':', ""ccs_val""))) AS ""embeddingMedium_code_str"" FROM SpecimenPreparationSequence_unnested WHERE ""cnc_csd"" = 'SCT' AND ""cnc_val"" = '430863003' -- CodeMeaning is 'Embedding medium' GROUP BY ""SOPInstanceUID"" ), slide_staining AS ( SELECT ""SOPInstanceUID"", ARRAY_AGG(DISTINCT(CONCAT(""ccs_cm"", ':', ""ccs_csd"", ':', ""ccs_val""))) AS ""staining_usingSubstance_code_str"" FROM SpecimenPreparationSequence_unnested WHERE ""cnc_csd"" = 'SCT' AND ""cnc_val"" = '424361007' -- CodeMeaning is 'Using substance' GROUP BY ""SOPInstanceUID"" ), embedding_data AS ( SELECT d.""SOPInstanceUID"", d.""instance_size"", e.""embeddingMedium_code_str"", s.""staining_usingSubstance_code_str"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" AS d LEFT JOIN slide_embedding AS e ON d.""SOPInstanceUID"" = e.""SOPInstanceUID"" LEFT JOIN slide_staining AS s ON d.""SOPInstanceUID"" = s.""SOPInstanceUID"" WHERE d.""Modality"" = 'SM' ) SELECT SPLIT_PART(embeddingMedium_CodeMeaning_flat.VALUE::STRING, ':', 1) AS ""embeddingMedium_CodeMeaning"", SPLIT_PART(staining_usingSubstance_CodeMeaning_flat.VALUE::STRING, ':', 1) AS ""staining_usingSubstance_CodeMeaning"", COUNT(*) AS ""count_"" FROM embedding_data , LATERAL FLATTEN(input => embedding_data.""embeddingMedium_code_str"") AS embeddingMedium_CodeMeaning_flat , LATERAL FLATTEN(input => embedding_data.""staining_usingSubstance_code_str"") AS staining_usingSubstance_CodeMeaning_flat GROUP BY SPLIT_PART(embeddingMedium_CodeMeaning_flat.VALUE::STRING, ':', 1), SPLIT_PART(staining_usingSubstance_CodeMeaning_flat.VALUE::STRING, ':', 1); ",snow,sf_bq421,dicom_all.modality; dicom_all.sopinstanceuid; dicom_all.specimendescriptionsequence,3,2100,True,fix,True,sf_bq421 sf_bq422,IDC,snowflake,"Using the 'nlst' collection's CT images, calculate and compare two separate metrics: 1) The average series size in MiB for the top 3 patients with the highest slice interval difference tolerance (defined as the difference between the maximum and minimum unique slice intervals across all their series), and 2) The average series size in MiB for the top 3 patients with the highest exposure difference (defined as the difference between the maximum and minimum unique exposure values across all their series). For each patient, calculate the series size by summing the instance sizes of all images in that series and converting to MiB. Return the results as two separate groups labeled ""Top 3 by Slice Interval"" and ""Top 3 by Max Exposure"" with their respective average series sizes.","WITH f AS ( SELECT ""PatientID"", ""SeriesInstanceUID"", ""instance_size"", ""SpacingBetweenSlices"", ""SliceThickness"", ""Exposure"", ""ExposureInmAs"", ""Modality"", ""collection_name"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" WHERE UPPER(""collection_name"") = 'NLST' AND ""Modality"" = 'CT' ), series_sizes AS ( SELECT ""PatientID"", ""SeriesInstanceUID"", SUM(COALESCE(""instance_size"", 0))::FLOAT / (1024 * 1024) AS series_size_mib FROM f GROUP BY ""PatientID"", ""SeriesInstanceUID"" ), patient_slice_intervals AS ( SELECT DISTINCT ""PatientID"", COALESCE(TRY_TO_DECIMAL(""SpacingBetweenSlices""), TRY_TO_DECIMAL(""SliceThickness"")) AS slice_interval FROM f WHERE COALESCE(TRY_TO_DECIMAL(""SpacingBetweenSlices""), TRY_TO_DECIMAL(""SliceThickness"")) IS NOT NULL ), patient_slice_diff AS ( SELECT ""PatientID"", MAX(slice_interval) - MIN(slice_interval) AS slice_diff FROM patient_slice_intervals GROUP BY ""PatientID"" ), top3_by_slice AS ( SELECT ""PatientID"" FROM patient_slice_diff ORDER BY slice_diff DESC NULLS LAST LIMIT 3 ), patient_exposure_values AS ( SELECT DISTINCT ""PatientID"", COALESCE(CAST(""ExposureInmAs"" AS FLOAT), CAST(TRY_TO_DECIMAL(""Exposure"") AS FLOAT)) AS exposure_val FROM f WHERE COALESCE(CAST(""ExposureInmAs"" AS FLOAT), CAST(TRY_TO_DECIMAL(""Exposure"") AS FLOAT)) IS NOT NULL ), patient_exposure_diff AS ( SELECT ""PatientID"", MAX(exposure_val) - MIN(exposure_val) AS exp_diff FROM patient_exposure_values GROUP BY ""PatientID"" ), top3_by_exposure AS ( SELECT ""PatientID"" FROM patient_exposure_diff ORDER BY exp_diff DESC NULLS LAST LIMIT 3 ) SELECT 'Top 3 by Slice Interval' AS ""Label"", AVG(s.series_size_mib) AS ""Average Series Size MiB"" FROM series_sizes s JOIN top3_by_slice t USING (""PatientID"") UNION ALL SELECT 'Top 3 by Max Exposure' AS ""Label"", AVG(s.series_size_mib) AS ""Average Series Size MiB"" FROM series_sizes s JOIN top3_by_exposure t USING (""PatientID"");",snow,sf_bq422,dicom_all.collection_name; dicom_all.exposure; dicom_all.exposureinmas; dicom_all.instance_size; dicom_all.modality; dicom_all.patientid; dicom_all.seriesinstanceuid; dicom_all.slicethickness; dicom_all.spacingbetweenslices,9,2100,True,ok,False,sf_bq422 sf_bq424,WORLD_BANK,bigquery,"List the top 10 countries with respect to the total amount of long-term external debt in descending order, excluding those without a specified region.","SELECT DISTINCT id.country_name, --cs.region, id.value AS debt, --id.indicator_code FROM ( SELECT country_code, region FROM `bigquery-public-data.world_bank_intl_debt.country_summary` WHERE region != """" ) cs INNER JOIN ( SELECT country_code, country_name, value, indicator_code FROM `bigquery-public-data.world_bank_intl_debt.international_debt` WHERE indicator_code = ""DT.AMT.DLXF.CD"") id ON cs.country_code = id.country_code ORDER BY id.value DESC LIMIT 10",lite,bq424,country_summary.country_code; country_summary.region; international_*.country_code; international_*.country_name; international_*.indicator_code; international_*.value,6,144,True,ok,False,bq424 sf_bq425,EBI_CHEMBL,bigquery,"Using data from ChEMBL Release 23, retrieve all distinct molecules associated with the company 'SanofiAventis,' listing the trade name and the most recent approval date for each molecule. Make sure to keep only the latest approval date per molecule and ensure the company field precisely matches 'SanofiAventis' without relying on other fields.","SELECT * FROM ( SELECT molregno, comp.company, prod.trade_name, prod.approval_date, ROW_NUMBER() OVER(PARTITION BY molregno ORDER BY PARSE_DATE('%Y-%m-%d', prod.approval_date) DESC) rn FROM bigquery-public-data.ebi_chembl.compound_records_23 AS cmpd_rec JOIN bigquery-public-data.ebi_chembl.molecule_synonyms_23 AS ms USING (molregno) JOIN bigquery-public-data.ebi_chembl.research_companies_23 AS comp USING (res_stem_id) JOIN bigquery-public-data.ebi_chembl.formulations_23 AS form USING (molregno) JOIN bigquery-public-data.ebi_chembl.products_23 AS prod USING (product_id) ) as subq WHERE rn = 1 AND company = 'SanofiAventis'",lite,bq425,compound_records_23.molregno; formulations_*.molregno; formulations_*.product_id; molecule_synonyms_*.molregno; molecule_synonyms_*.res_stem_id; products_*.approval_date; products_*.product_id; products_*.trade_name; research_companies_*.company; research_companies_*.res_stem_id,10,816,True,fix,True,bq425 sf_bq428,NCAA_BASKETBALL,bigquery,"For the top five team markets with the highest number of distinct players who scored at least 15 points during the second period of games between 2010 and 2018, provide details of each game they played in NCAA basketball historical tournament matches during the same period, as specified in the data model document.","WITH top_teams AS ( SELECT team_market FROM ( SELECT team_market, player_id AS id, SUM(points_scored) FROM `bigquery-public-data.ncaa_basketball.mbb_pbp_sr` WHERE season >= 2010 AND season <=2018 AND period = 2 GROUP BY game_id, team_market, player_id HAVING SUM(points_scored) >= 15) C GROUP BY team_market HAVING COUNT(DISTINCT id) > 5 ORDER BY COUNT(DISTINCT id) DESC LIMIT 5 ) SELECT season, round, days_from_epoch, game_date, day, 'win' AS label, win_seed AS seed, win_market AS market, win_name AS name, win_alias AS alias, win_school_ncaa AS school_ncaa, lose_seed AS opponent_seed, lose_market AS opponent_market, lose_name AS opponent_name, lose_alias AS opponent_alias, lose_school_ncaa AS opponent_school_ncaa FROM `bigquery-public-data.ncaa_basketball.mbb_historical_tournament_games` JOIN top_teams ON top_teams.team_market = win_market WHERE season >= 2010 AND season <=2018 UNION ALL SELECT season, round, days_from_epoch, game_date, day, 'loss' AS label, lose_seed AS seed, lose_market AS market, lose_name AS name, lose_alias AS alias, lose_school_ncaa AS school_ncaa, win_seed AS opponent_seed, win_market AS opponent_market, win_name AS opponent_name, win_alias AS opponent_alias, win_school_ncaa AS opponent_school_ncaa FROM `bigquery-public-data.ncaa_basketball.mbb_historical_tournament_games` JOIN top_teams ON top_teams.team_market = lose_market WHERE season >= 2010 AND season <=2018 ",lite,bq428,mbb_historical_tournament_games.day; mbb_historical_tournament_games.days_from_epoch; mbb_historical_tournament_games.game_date; mbb_historical_tournament_games.lose_alias; mbb_historical_tournament_games.lose_market; mbb_historical_tournament_games.lose_name; mbb_historical_tournament_games.lose_school_ncaa; mbb_historical_tournament_games.lose_seed; mbb_historical_tournament_games.round; mbb_historical_tournament_games.season; mbb_historical_tournament_games.win_alias; mbb_historical_tournament_games.win_market; mbb_historical_tournament_games.win_name; mbb_historical_tournament_games.win_school_ncaa; mbb_historical_tournament_games.win_seed; mbb_pbp_sr.game_id; mbb_pbp_sr.period; mbb_pbp_sr.player_id; mbb_pbp_sr.points_scored; mbb_pbp_sr.season; mbb_pbp_sr.team_market,21,505,True,fix,True,bq428 sf_bq429,CENSUS_BUREAU_ACS_2,snowflake,"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?","WITH income_diff_by_zip AS ( SELECT T1.""geo_id"", ABS(T2.""median_income"" - T1.""median_income"") AS income_difference FROM ""CENSUS_BUREAU_ACS_2"".""CENSUS_BUREAU_ACS"".""ZCTA5_2015_5YR"" AS T1 JOIN ""CENSUS_BUREAU_ACS_2"".""CENSUS_BUREAU_ACS"".""ZCTA5_2018_5YR"" AS T2 ON T1.""geo_id"" = T2.""geo_id"" WHERE T1.""median_income"" IS NOT NULL AND T2.""median_income"" IS NOT NULL ), vulnerable_pop_by_zip AS ( SELECT ""geo_id"", (""employed_wholesale_trade"" * 0.38423645320197042 + (""employed_agriculture_forestry_fishing_hunting_mining"" + ""employed_construction"") * 0.48071410777129553 + ""employed_arts_entertainment_recreation_accommodation_food"" * 0.89455676291236841 + ""employed_information"" * 0.31315240083507306 + ""employed_retail_trade"" * 0.51) AS vulnerable_employees FROM ""CENSUS_BUREAU_ACS_2"".""CENSUS_BUREAU_ACS"".""ZCTA5_2017_5YR"" WHERE ""employed_wholesale_trade"" IS NOT NULL AND ""employed_agriculture_forestry_fishing_hunting_mining"" IS NOT NULL AND ""employed_construction"" IS NOT NULL AND ""employed_arts_entertainment_recreation_accommodation_food"" IS NOT NULL AND ""employed_information"" IS NOT NULL AND ""employed_retail_trade"" IS NOT NULL ), joined_data AS ( SELECT T3.""state_name"", T1.income_difference, T2.vulnerable_employees FROM income_diff_by_zip AS T1 JOIN vulnerable_pop_by_zip AS T2 ON T1.""geo_id"" = T2.""geo_id"" JOIN ""CENSUS_BUREAU_ACS_2"".""GEO_US_BOUNDARIES"".""ZIP_CODES"" AS T3 ON T1.""geo_id"" = T3.""zip_code"" ) SELECT ""state_name"", AVG(income_difference) AS avg_income_diff, AVG(vulnerable_employees) AS avg_vulnerable_employees FROM joined_data GROUP BY ""state_name"" ORDER BY avg_income_diff DESC LIMIT 5",snow,sf_bq429,zcta5_2015_5yr.geo_id; zcta5_2015_5yr.median_income; zcta_*.employed_agriculture_forestry_fishing_hunting_mining; zcta_*.employed_arts_entertainment_recreation_accommodation_food; zcta_*.employed_construction; zcta_*.employed_information; zcta_*.employed_retail_trade; zcta_*.employed_wholesale_trade; zcta_*.geo_id; zcta_*.median_income; zip_codes.state_name; zip_codes.zip_code,12,14419,True,fix,True,sf_bq429 sf_bq430,EBI_CHEMBL,bigquery,"Find pairs of different molecules tested in the same assay and standard type, where both have 10–15 heavy atoms, fewer than 5 activities in that assay, fewer than 2 duplicate activities, non-null standard values, and pChEMBL values over 10. For each pair, report the maximum heavy atom count, the latest publication date (calculated based on the document's rank within the same journal and year, and map it to a synthetic month and day), the highest document ID, classify the change in standard values as 'increase', 'decrease', or 'no-change' based on their values and relations, and generate UUIDs from their activity IDs and canonical SMILES.","select -- *, greatest(heavy_atoms_1, heavy_atoms_2) as heavy_atoms_greatest, greatest(publication_date_1, publication_date_2) as publication_date_greatest, greatest(doc_id_1, doc_id_2) as doc_id_greatest, case when standard_value_1 > standard_value_2 and standard_relation_1 not in ('<', '<<') and standard_relation_2 not in ('>', '>>') then 'decrease' when standard_value_1 < standard_value_2 and standard_relation_1 not in ('>', '>>') and standard_relation_2 not in ('<', '<<') then 'increase' when standard_value_1 = standard_value_2 and standard_relation_1 in ('=', '~') and standard_relation_2 in ('=', '~') then 'no-change' else null end as standard_change, to_hex(md5(to_json_string(struct(activity_id_1, activity_id_2)))) as mmp_delta_uuid, to_hex(md5(to_json_string(struct(canonical_smiles_1, canonical_smiles_2, 5)))) as mmp_search_uuid from ( select act.assay_id, act.standard_type, act.activity_id as activity_id_1, cast(act.standard_value as numeric) as standard_value_1, act.standard_relation as standard_relation_1, cast(act.pchembl_value as numeric) as pchembl_value_1, count(*) over (partition by act.assay_id) as count_activities_1, count(*) over (partition by act.assay_id, act.molregno) as duplicate_activities_1, act.molregno as molregno_1, com.canonical_smiles as canonical_smiles_1, cast(cmp.heavy_atoms as int64) as heavy_atoms_1, cast(d.doc_id as int64) as doc_id_1, date( coalesce(cast(d.year as int64), 1970), coalesce(cast(floor(percent_rank() over ( partition by d.journal, d.year order by SAFE_CAST(d.first_page as int64)) * 11) as int64) + 1, 1), coalesce(mod(cast(floor(percent_rank() over ( partition by d.journal, d.year order by SAFE_CAST(d.first_page as int64)) * 308) as int64), 28) + 1, 1)) as publication_date_1 FROM `bigquery-public-data.ebi_chembl.activities_29` act join `bigquery-public-data.ebi_chembl.compound_structures_29` com using (molregno) join `bigquery-public-data.ebi_chembl.compound_properties_29` cmp using (molregno) left join `bigquery-public-data.ebi_chembl.docs_29` d using (doc_id) where standard_type in (select distinct standard_type from`bigquery-public-data.ebi_chembl.activities_29` where pchembl_value is not null) ) a1 join ( select act.assay_id, act.standard_type, act.activity_id as activity_id_2, cast(act.standard_value as numeric) as standard_value_2, act.standard_relation as standard_relation_2, cast(act.pchembl_value as numeric) as pchembl_value_2, count(*) over (partition by act.assay_id) as count_activities_2, count(*) over (partition by act.assay_id, act.molregno) as duplicate_activities_2, act.molregno as molregno_2, com.canonical_smiles as canonical_smiles_2, cast(cmp.heavy_atoms as int64) as heavy_atoms_2, cast(d.doc_id as int64) as doc_id_2, date( coalesce(cast(d.year as int64), 1970), coalesce(cast(floor(percent_rank() over ( partition by d.journal, d.year order by SAFE_CAST(d.first_page as int64)) * 11) as int64) + 1, 1), coalesce(mod(cast(floor(percent_rank() over ( partition by d.journal, d.year order by SAFE_CAST(d.first_page as int64)) * 308) as int64), 28) + 1, 1)) as publication_date_2 FROM `bigquery-public-data.ebi_chembl.activities_29` act join `bigquery-public-data.ebi_chembl.compound_structures_29` com using (molregno) join `bigquery-public-data.ebi_chembl.compound_properties_29` cmp using (molregno) left join `bigquery-public-data.ebi_chembl.docs_29` d using (doc_id) where standard_type in (select distinct standard_type from`bigquery-public-data.ebi_chembl.activities_29` where pchembl_value is not null) ) a2 using (assay_id, standard_type) where a1.molregno_1 != a2.molregno_2 and a1.count_activities_1 < 5 and a2.count_activities_2 < 5 and a1.heavy_atoms_1 between 10 and 15 and a2.heavy_atoms_2 between 10 and 15 and a1.standard_value_1 is not null and a2.standard_value_2 is not null and a1.duplicate_activities_1 < 2 and a2.duplicate_activities_2 < 2 and a1.pchembl_value_1 > 10 and a2.pchembl_value_2 > 10 ",lite,bq430,activities_*.activity_id; activities_*.assay_id; activities_*.doc_id; activities_*.molregno; activities_*.pchembl_value; activities_*.standard_relation; activities_*.standard_type; activities_*.standard_value; compound_properties_*.heavy_atoms; compound_properties_*.molregno; compound_structures_*.canonical_smiles; compound_structures_*.molregno; docs_*.doc_id; docs_*.first_page; docs_*.journal; docs_*.year,16,816,True,fix,True,bq430 sf_bq442,CYMBAL_INVESTMENTS,bigquery,Please collect the information of the top 6 trade report with the highest closing prices. Refer to the document for all the information I want.,"SELECT OrderID AS tradeID, MaturityDate AS tradeTimestamp, ( CASE SUBSTR(TargetCompID, 0, 4) WHEN 'MOMO' THEN 'Momentum' WHEN 'LUCK' THEN 'Feeling Lucky' WHEN 'PRED' THEN 'Prediction' END ) AS algorithm, Symbol AS symbol, LastPx AS openPrice, StrikePrice AS closePrice, ( SELECT Side FROM UNNEST(Sides) ) AS tradeDirection, (CASE ( SELECT Side FROM UNNEST(Sides)) WHEN 'SHORT' THEN -1 WHEN 'LONG' THEN 1 END ) AS tradeMultiplier FROM `bigquery-public-data.cymbal_investments.trade_capture_report`cv ORDER BY closePrice DESC LIMIT 6",lite,bq442,trade_capture_report.lastpx; trade_capture_report.maturitydate; trade_capture_report.orderid; trade_capture_report.sides; trade_capture_report.strikeprice; trade_capture_report.symbol; trade_capture_report.targetcompid,7,14,True,ok,False,bq442 sf_bq444,CRYPTO,snowflake,"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.","WITH events AS ( SELECT CASE WHEN ""topics""[0]::STRING = '0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde' THEN 'MINT' ELSE 'BURN' END AS ""event_type"", ""block_timestamp"", ""block_number"", ""transaction_hash"", ""log_index"" FROM ""CRYPTO"".""CRYPTO_ETHEREUM"".""LOGS"" WHERE LOWER(""address"") = '0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8' AND ""topics""[0]::STRING IN ( '0x7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde', '0x0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c' ) ), ranked_events AS ( SELECT ""event_type"", ""block_timestamp"", ""block_number"", ""transaction_hash"", ROW_NUMBER() OVER ( PARTITION BY ""event_type"" ORDER BY ""block_timestamp"", ""block_number"", ""log_index"" ) AS ""rn"" FROM events ) SELECT ""event_type"", TO_TIMESTAMP_NTZ(""block_timestamp"" / 1000000) AS ""block_timestamp"", ""block_number"", ""transaction_hash"" FROM ranked_events WHERE ""rn"" <= 5 ORDER BY ""block_timestamp"", ""block_number"", ""event_type"", ""transaction_hash""",snow,sf_bq444,logs.address; logs.block_number; logs.block_timestamp; logs.log_index; logs.topics; logs.transaction_hash,6,286,True,fix,False,sf_bq444 sf_bq452,_1000_GENOMES,bigquery,"Identify variants on chromosome 12 and, for each variant, calculate the chi-squared score using allele counts in cases and controls, where cases are individuals from the 'EAS' super population and controls are individuals from all other super populations. Apply Yates's correction for continuity in the chi-squared calculation, ensuring that the expected counts for each allele in both groups are at least 5. Return the start position, end position, and chi-squared score of the top variants where the chi-squared score is no less than 29.71679.","SELECT * FROM ( SELECT `start`, `end`, ROUND( POW(ABS(case_ref_count - (ref_count / allele_count) * case_count) - 0.5, 2) / ((ref_count / allele_count) * case_count) + POW(ABS(control_ref_count - (ref_count / allele_count) * control_count) - 0.5, 2) / ((ref_count / allele_count) * control_count) + POW(ABS(case_alt_count - (alt_count / allele_count) * case_count) - 0.5, 2) / ((alt_count / allele_count) * case_count) + POW(ABS(control_alt_count - (alt_count / allele_count) * control_count) - 0.5, 2) / ((alt_count / allele_count) * control_count), 3 ) AS chi_squared_score FROM ( SELECT reference_name, `start`, `end`, reference_bases, alternate_bases, vt, SUM(ref_count + alt_count) AS allele_count, SUM(ref_count) AS ref_count, SUM(alt_count) AS alt_count, SUM(IF(is_case, CAST(ref_count + alt_count AS INT64), 0)) AS case_count, SUM(IF(NOT is_case, CAST(ref_count + alt_count AS INT64), 0)) AS control_count, SUM(IF(is_case, ref_count, 0)) AS case_ref_count, SUM(IF(is_case, alt_count, 0)) AS case_alt_count, SUM(IF(NOT is_case, ref_count, 0)) AS control_ref_count, SUM(IF(NOT is_case, alt_count, 0)) AS control_alt_count FROM ( SELECT v.reference_name, v.`start`, v.`end`, v.reference_bases, v.alternate_bases, v.vt, ('EAS' = p.super_population) AS is_case, IF(call.genotype[SAFE_OFFSET(0)] = 0, 1, 0) AS ref_count, IF(call.genotype[SAFE_OFFSET(0)] = 1, 1, 0) AS alt_count FROM `spider2-public-data.1000_genomes.variants` AS v, UNNEST(v.call) AS call JOIN `spider2-public-data.1000_genomes.sample_info` AS p ON call.call_set_name = p.sample WHERE v.reference_name = '12' ) GROUP BY reference_name, `start`, `end`, reference_bases, alternate_bases, vt ) WHERE (ref_count / allele_count) * case_count >= 5.0 AND (ref_count / allele_count) * control_count >= 5.0 AND (alt_count / allele_count) * case_count >= 5.0 AND (alt_count / allele_count) * control_count >= 5.0 ) WHERE chi_squared_score >= 29.71679 ORDER BY chi_squared_score DESC",lite,bq452,sample_info.sample; sample_info.super_population; variants.alternate_bases; variants.call; variants.end; variants.reference_bases; variants.reference_name; variants.start; variants.vt,9,114,True,ok,False,bq452 sf_bq453,_1000_GENOMES,bigquery,"In chromosome 17 between positions 41196311 and 41277499, what are the reference names, start and end positions, reference bases, distinct alternate bases, variant types, and the chi-squared scores (calculated from Hardy-Weinberg equilibrium) along with the total number of genotypes, their observed and expected counts for homozygous reference, heterozygous, and homozygous alternate genotypes, as well as allele frequencies (including those from 1KG), for each variant?","SELECT reference_name, start, `END`, reference_bases, alt, vt, POW(hom_ref_count - expected_hom_ref_count, 2) / expected_hom_ref_count + POW(hom_alt_count - expected_hom_alt_count, 2) / expected_hom_alt_count + POW(het_count - expected_het_count, 2) / expected_het_count AS chi_squared_score, total_count, hom_ref_count, expected_hom_ref_count AS expected_hom_ref_count, het_count, expected_het_count AS expected_het_count, hom_alt_count, expected_hom_alt_count AS expected_hom_alt_count, alt_freq AS alt_freq, alt_freq_from_1KG FROM ( SELECT reference_name, start, `END`, reference_bases, alt, vt, alt_freq_from_1KG, hom_ref_freq + (0.5 * het_freq) AS hw_ref_freq, 1 - (hom_ref_freq + (0.5 * het_freq)) AS alt_freq, POW(hom_ref_freq + (0.5 * het_freq), 2) * total_count AS expected_hom_ref_count, POW(1 - (hom_ref_freq + (0.5 * het_freq)), 2) * total_count AS expected_hom_alt_count, 2 * (hom_ref_freq + (0.5 * het_freq)) * (1 - (hom_ref_freq + (0.5 * het_freq))) * total_count AS expected_het_count, total_count, hom_ref_count, het_count, hom_alt_count, hom_ref_freq, het_freq, hom_alt_freq FROM ( SELECT reference_name, start, `END`, reference_bases, STRING_AGG(DISTINCT alternate_base) AS alt, vt, af AS alt_freq_from_1KG, COUNTIF(first_allele IN (0, 1) AND second_allele IN (0, 1)) AS total_count, COUNTIF(first_allele = 0 AND second_allele = 0) AS hom_ref_count, COUNTIF((first_allele = 0 AND second_allele = 1) OR (first_allele = 1 AND second_allele = 0)) AS het_count, COUNTIF(first_allele = 1 AND second_allele = 1) AS hom_alt_count, SAFE_DIVIDE(COUNTIF(first_allele = 0 AND second_allele = 0), COUNTIF(first_allele IN (0, 1) AND second_allele IN (0, 1))) AS hom_ref_freq, SAFE_DIVIDE(COUNTIF((first_allele = 0 AND second_allele = 1) OR (first_allele = 1 AND second_allele = 0)), COUNTIF(first_allele IN (0, 1) AND second_allele IN (0, 1))) AS het_freq, SAFE_DIVIDE(COUNTIF(first_allele = 1 AND second_allele = 1), COUNTIF(first_allele IN (0, 1) AND second_allele IN (0, 1))) AS hom_alt_freq FROM ( SELECT reference_name, start, `END`, reference_bases, vt, af, call.call_set_name, call.genotype[OFFSET(0)] AS first_allele, call.genotype[OFFSET(1)] AS second_allele, alternate_base FROM `spider2-public-data.1000_genomes.variants`, UNNEST(call) AS call, UNNEST(alternate_bases) AS alternate_base WHERE reference_name = '17' AND start BETWEEN 41196311 AND 41277499 ) GROUP BY reference_name, start, `END`, reference_bases, vt, af ) ) ",lite,bq453,variants.af; variants.alternate_bases; variants.call; variants.end; variants.reference_bases; variants.reference_name; variants.start; variants.vt,8,114,True,ok,False,bq453 sf_bq455,IDC,snowflake,"Identify the top five CT scan series by size (in MiB), including their SeriesInstanceUID, series number, patient ID, and series size. These series must be from the CT modality and not part of the 'nlst' collection. Exclude any series where the ImageType is classified as 'LOCALIZER' or where the TransferSyntaxUID is either '1.2.840.10008.1.2.4.70' or '1.2.840.10008.1.2.4.51' (i.e., JPEG compressed). The selected series must have consistent slice intervals, exposure levels, image orientation (with only one unique ImageOrientationPatient value), pixel spacing, image positions (both z-axis and xy positions), and pixel dimensions (rows and columns). Ensure that the number of images matches the number of unique z-axis positions, indicating no duplicate slices. Additionally, the z-axis component of the cross product of the x and y direction cosines from ImageOrientationPatient must have an absolute value between 0.99 and 1.01, ensuring alignment with the expected imaging plane. Finally, order the results by series size in descending order and limit the output to the top five series satisfying these conditions.","SELECT sm.""SeriesInstanceUID"", sm.""SeriesNumber"", sm.""PatientID"", sm.""series_size_mib"" FROM ( SELECT wd.""SeriesInstanceUID"", MIN(wd.""SeriesNumber"") AS ""SeriesNumber"", MIN(wd.""PatientID"") AS ""PatientID"", SUM(wd.""instance_size"") / 1048576.0 AS ""series_size_mib"", COUNT(*) AS ""image_count"", COUNT(DISTINCT wd.""pos_z_r"") AS ""unique_z_count"", COUNT(DISTINCT wd.""pos_xy_key"") AS ""unique_xy_count"", COUNT(DISTINCT wd.""ps_row_r"") AS ""ps_row_count"", COUNT(DISTINCT wd.""ps_col_r"") AS ""ps_col_count"", COUNT(DISTINCT wd.""Rows"") AS ""rows_count"", COUNT(DISTINCT wd.""Columns"") AS ""cols_count"", COUNT(DISTINCT wd.""orientation_raw"") AS ""orientation_count"", COUNT(DISTINCT wd.""exposure_inmas_r"") AS ""exposure_inmas_count"", COUNT(DISTINCT wd.""exposure_r"") AS ""exposure_count"", COUNT(DISTINCT wd.""tube_current_r"") AS ""tube_current_count"", COUNT(DISTINCT CASE WHEN wd.""z_diff"" IS NOT NULL THEN wd.""z_diff"" END) AS ""distinct_z_diff_count"", MIN(wd.""z_diff"") AS ""min_z_diff"", MAX(wd.""z_diff"") AS ""max_z_diff"", MIN(wd.""cross_z"") AS ""min_cross_z"", MAX(wd.""cross_z"") AS ""max_cross_z"" FROM ( SELECT f.""SeriesInstanceUID"", f.""SeriesNumber"", f.""PatientID"", f.""instance_size"", CONCAT(TO_VARCHAR(f.""pos_x_r""), '|', TO_VARCHAR(f.""pos_y_r"")) AS ""pos_xy_key"", f.""pos_z"", f.""pos_z_r"", f.""ps_row_r"", f.""ps_col_r"", f.""Rows"", f.""Columns"", f.""orientation_raw"", f.""exposure_inmas_r"", f.""exposure_r"", f.""tube_current_r"", f.""cross_z"", ROUND(ABS(LEAD(f.""pos_z"") OVER (PARTITION BY f.""SeriesInstanceUID"" ORDER BY f.""pos_z"") - f.""pos_z""), 5) AS ""z_diff"" FROM ( SELECT da.""SeriesInstanceUID"", da.""SeriesNumber"", da.""PatientID"", da.""instance_size"", TRY_TO_DOUBLE(da.""ImagePositionPatient""[2]::STRING) AS ""pos_z"", ROUND(TRY_TO_DOUBLE(da.""ImagePositionPatient""[0]::STRING), 5) AS ""pos_x_r"", ROUND(TRY_TO_DOUBLE(da.""ImagePositionPatient""[1]::STRING), 5) AS ""pos_y_r"", ROUND(TRY_TO_DOUBLE(da.""ImagePositionPatient""[2]::STRING), 5) AS ""pos_z_r"", ROUND(TRY_TO_DOUBLE(da.""PixelSpacing""[0]::STRING), 5) AS ""ps_row_r"", ROUND(TRY_TO_DOUBLE(da.""PixelSpacing""[1]::STRING), 5) AS ""ps_col_r"", da.""Rows"", da.""Columns"", TO_VARCHAR(da.""ImageOrientationPatient"") AS ""orientation_raw"", ROUND(TRY_TO_DOUBLE(da.""ExposureInmAs""::STRING), 4) AS ""exposure_inmas_r"", ROUND(TRY_TO_DOUBLE(da.""Exposure""::STRING), 4) AS ""exposure_r"", ROUND(TRY_TO_DOUBLE(da.""XRayTubeCurrentInmA""::STRING), 4) AS ""tube_current_r"", TRY_TO_DOUBLE(da.""ImageOrientationPatient""[0]::STRING) * TRY_TO_DOUBLE(da.""ImageOrientationPatient""[4]::STRING) - TRY_TO_DOUBLE(da.""ImageOrientationPatient""[1]::STRING) * TRY_TO_DOUBLE(da.""ImageOrientationPatient""[3]::STRING) AS ""cross_z"" FROM ""IDC"".""IDC_V17"".""DICOM_ALL"" da WHERE NVL(UPPER(da.""collection_name""), '') != 'NLST' AND da.""Modality"" = 'CT' AND da.""TransferSyntaxUID"" NOT IN ('1.2.840.10008.1.2.4.70', '1.2.840.10008.1.2.4.51') AND NOT (UPPER(TO_VARCHAR(da.""ImageType"")) LIKE '%LOCALIZER%') AND da.""SeriesInstanceUID"" IS NOT NULL AND da.""SeriesNumber"" IS NOT NULL AND da.""PatientID"" IS NOT NULL AND da.""ImagePositionPatient"" IS NOT NULL AND da.""ImageOrientationPatient"" IS NOT NULL AND da.""PixelSpacing"" IS NOT NULL AND TRY_TO_DOUBLE(da.""ImagePositionPatient""[0]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""ImagePositionPatient""[1]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""ImagePositionPatient""[2]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""PixelSpacing""[0]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""PixelSpacing""[1]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""ImageOrientationPatient""[0]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""ImageOrientationPatient""[1]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""ImageOrientationPatient""[3]::STRING) IS NOT NULL AND TRY_TO_DOUBLE(da.""ImageOrientationPatient""[4]::STRING) IS NOT NULL ) f ) wd GROUP BY wd.""SeriesInstanceUID"" ) sm WHERE sm.""image_count"" = sm.""unique_z_count"" AND sm.""unique_xy_count"" = 1 AND sm.""ps_row_count"" = 1 AND sm.""ps_col_count"" = 1 AND sm.""rows_count"" = 1 AND sm.""cols_count"" = 1 AND sm.""orientation_count"" = 1 AND sm.""distinct_z_diff_count"" <= 1 AND (sm.""distinct_z_diff_count"" = 0 OR sm.""min_z_diff"" = sm.""max_z_diff"") AND sm.""exposure_inmas_count"" <= 1 AND sm.""exposure_count"" <= 1 AND sm.""tube_current_count"" <= 1 AND ABS(sm.""min_cross_z"") BETWEEN 0.99 AND 1.01 AND ABS(sm.""max_cross_z"") BETWEEN 0.99 AND 1.01 ORDER BY sm.""series_size_mib"" DESC LIMIT 5;",snow,sf_bq455,dicom_all.collection_name; dicom_all.columns; dicom_all.exposure; dicom_all.exposureinmas; dicom_all.imageorientationpatient; dicom_all.imagepositionpatient; dicom_all.imagetype; dicom_all.instance_size; dicom_all.modality; dicom_all.patientid; dicom_all.pixelspacing; dicom_all.rows; dicom_all.seriesinstanceuid; dicom_all.seriesnumber; dicom_all.transfersyntaxuid; dicom_all.xraytubecurrentinma,16,2100,True,ok,False,sf_bq455 sf_ga001,GA4,snowflake,I want to know the preferences of customers who purchased the Google Navy Speckled Tee in December 2020. What other product was purchased with the highest total quantity alongside this item?,"WITH ""events_dec"" AS ( SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201201"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201202"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201203"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201204"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201205"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201206"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201207"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201208"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201209"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201210"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201211"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201212"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201213"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201214"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201215"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201216"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201217"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201218"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201219"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201220"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201221"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201222"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201223"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201224"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201225"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201226"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201227"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201228"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201229"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201230"" UNION ALL SELECT ""EVENT_NAME"",""EVENT_DATE"",""ECOMMERCE"",""ITEMS"" FROM ""GA4"".""GA4_OBFUSCATED_SAMPLE_ECOMMERCE"".""EVENTS_20201231"" ), ""purchase_items"" AS ( SELECT (""ECOMMERCE"":""transaction_id"")::string AS ""TRANSACTION_ID"", f.value:""item_id""::string AS ""ITEM_ID"", f.value:""item_name""::string AS ""ITEM_NAME"", COALESCE(f.value:""quantity""::number, 1) AS ""QUANTITY"" FROM ""events_dec"" e, LATERAL FLATTEN(input => e.""ITEMS"") f WHERE e.""EVENT_NAME"" = 'purchase' AND (""ECOMMERCE"":""transaction_id"") IS NOT NULL AND (""ECOMMERCE"":""transaction_id"")::string != '(not set)' ), ""tx_with_target"" AS ( SELECT DISTINCT ""TRANSACTION_ID"" FROM ""purchase_items"" WHERE UPPER(""ITEM_NAME"") = 'GOOGLE NAVY SPECKLED TEE' ) SELECT p.""ITEM_NAME"" AS ""OTHER_PRODUCT_NAME"", SUM(p.""QUANTITY"") AS ""TOTAL_QUANTITY_ALONGSIDE"" FROM ""purchase_items"" p JOIN ""tx_with_target"" t ON p.""TRANSACTION_ID"" = t.""TRANSACTION_ID"" WHERE UPPER(p.""ITEM_NAME"") != 'GOOGLE NAVY SPECKLED TEE' GROUP BY p.""ITEM_NAME"" ORDER BY SUM(p.""QUANTITY"") DESC, p.""ITEM_NAME"" ASC LIMIT 1;",snow,sf_ga001,events_*.ecommerce; events_*.event_name; events_*.items,3,23,True,fix,True,ga001 sf_ga002,GA4,bigquery,Tell me the most purchased other products and their quantities by customers who bought the Google Red Speckled Tee each month for the three months starting from November 2020.,"WITH Params AS ( SELECT 'Google Red Speckled Tee' AS selected_product ), DateRanges AS ( SELECT '20201101' AS start_date, '20201130' AS end_date, '202011' AS period UNION ALL SELECT '20201201', '20201231', '202012' UNION ALL SELECT '20210101', '20210131', '202101' ), PurchaseEvents AS ( SELECT period, user_pseudo_id, items FROM DateRanges JOIN `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` ON _TABLE_SUFFIX BETWEEN start_date AND end_date WHERE event_name = 'purchase' ), ProductABuyers AS ( SELECT DISTINCT period, user_pseudo_id FROM Params, PurchaseEvents, UNNEST(items) AS items WHERE items.item_name = selected_product ), TopProducts AS ( SELECT pe.period, items.item_name AS item_name, SUM(items.quantity) AS item_quantity FROM Params, PurchaseEvents pe, UNNEST(items) AS items WHERE user_pseudo_id IN (SELECT user_pseudo_id FROM ProductABuyers pb WHERE pb.period = pe.period) AND items.item_name != selected_product GROUP BY pe.period, items.item_name ), TopProductPerPeriod AS ( SELECT period, item_name, item_quantity FROM ( SELECT period, item_name, item_quantity, RANK() OVER (PARTITION BY period ORDER BY item_quantity DESC) AS rank FROM TopProducts ) WHERE rank = 1 ) SELECT period, item_name, item_quantity FROM TopProductPerPeriod ORDER BY period; ",lite,ga002,events_*.event_name; events_*.items; events_*.user_pseudo_id,3,23,True,ok,False,ga002 sf_ga003,FIREBASE,bigquery,"I'm trying to evaluate which board types were most effective on September 15, 2018. Can you find out the average scores for each board type from the quick play mode completions on that day?","WITH EventData AS ( SELECT user_pseudo_id, event_timestamp, param FROM `firebase-public-project.analytics_153293282.events_20180915`, UNNEST(event_params) AS param WHERE event_name = ""level_complete_quickplay"" AND (param.key = ""value"" OR param.key = ""board"") ), ProcessedData AS ( SELECT user_pseudo_id, event_timestamp, MAX(IF(param.key = ""value"", param.value.int_value, NULL)) AS score, MAX(IF(param.key = ""board"", param.value.string_value, NULL)) AS board_type FROM EventData GROUP BY user_pseudo_id, event_timestamp ) SELECT ANY_VALUE(board_type) AS board, AVG(score) AS average_score FROM ProcessedData GROUP BY board_type ",lite,ga003,events_*.event_name; events_*.event_params; events_*.event_timestamp; events_*.user_pseudo_id,4,20,True,ok,False,ga003 sf_ga004,GA4,bigquery,Can you figure out the average difference in pageviews between users who bought something and those who didn’t in December 2020? Just label anyone who was involved in purchase events as a purchaser.,"WITH UserInfo AS ( SELECT user_pseudo_id, COUNTIF(event_name = 'page_view') AS page_view_count, COUNTIF(event_name IN ('in_app_purchase', 'purchase')) AS purchase_event_count FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` WHERE _TABLE_SUFFIX BETWEEN '20201201' AND '20201231' GROUP BY 1 ), Averages AS ( SELECT (purchase_event_count > 0) AS purchaser, COUNT(*) AS user_count, SUM(page_view_count) AS total_page_views, SUM(page_view_count) / COUNT(*) AS avg_page_views FROM UserInfo GROUP BY 1 ) SELECT MAX(CASE WHEN purchaser THEN avg_page_views ELSE 0 END) - MAX(CASE WHEN NOT purchaser THEN avg_page_views ELSE 0 END) AS avg_page_views_difference FROM Averages;",lite,ga004,events_*.event_name; events_*.user_pseudo_id,2,23,True,ok,False,ga004 sf_ga008,GA4,bigquery,"Could you provide the total number of page views for each day in November 2020 as well as the average number of page views per user on those days, restricted to users who made at least one purchase in November 2020?","WITH UserInfo AS ( SELECT user_pseudo_id, PARSE_DATE('%Y%m%d', event_date) AS event_date, COUNTIF(event_name = 'page_view') AS page_view_count, COUNTIF(event_name = 'purchase') AS purchase_event_count FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` WHERE _TABLE_SUFFIX BETWEEN '20201101' AND '20201130' GROUP BY 1, 2 ) SELECT event_date, SUM(page_view_count) / COUNT(*) AS avg_page_views, SUM(page_view_count) FROM UserInfo WHERE purchase_event_count > 0 GROUP BY event_date ORDER BY event_date;",lite,ga008,events_*.event_date; events_*.event_name; events_*.user_pseudo_id,3,23,True,ok,False,ga008 sf_ga010,GA4,bigquery,Can you give me an overview of our website traffic for December 2020? I'm particularly interested in the channel with the fourth highest number of sessions.,"WITH prep AS ( SELECT user_pseudo_id, (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS session_id, ARRAY_AGG((SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'source') IGNORE NULLS ORDER BY event_timestamp)[SAFE_OFFSET(0)] AS source, ARRAY_AGG((SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium') IGNORE NULLS ORDER BY event_timestamp)[SAFE_OFFSET(0)] AS medium, ARRAY_AGG((SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'campaign') IGNORE NULLS ORDER BY event_timestamp)[SAFE_OFFSET(0)] AS campaign FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` WHERE _TABLE_SUFFIX BETWEEN '20201201' AND '20201231' GROUP BY user_pseudo_id, session_id ) SELECT -- session default channel grouping (dimension | the channel group associated with a session) CASE WHEN source = '(direct)' AND (medium IN ('(not set)','(none)')) THEN 'Direct' WHEN REGEXP_CONTAINS(campaign, 'cross-network') THEN 'Cross-network' WHEN (REGEXP_CONTAINS(source,'alibaba|amazon|google shopping|shopify|etsy|ebay|stripe|walmart') OR REGEXP_CONTAINS(campaign, '^(.*(([^a-df-z]|^)shop|shopping).*)$')) AND REGEXP_CONTAINS(medium, '^(.*cp.*|ppc|paid.*)$') THEN 'Paid Shopping' WHEN REGEXP_CONTAINS(source,'baidu|bing|duckduckgo|ecosia|google|yahoo|yandex') AND REGEXP_CONTAINS(medium,'^(.*cp.*|ppc|paid.*)$') THEN 'Paid Search' WHEN REGEXP_CONTAINS(source,'badoo|facebook|fb|instagram|linkedin|pinterest|tiktok|twitter|whatsapp') AND REGEXP_CONTAINS(medium,'^(.*cp.*|ppc|paid.*)$') THEN 'Paid Social' WHEN REGEXP_CONTAINS(source,'dailymotion|disneyplus|netflix|youtube|vimeo|twitch|vimeo|youtube') AND REGEXP_CONTAINS(medium,'^(.*cp.*|ppc|paid.*)$') THEN 'Paid Video' WHEN medium IN ('display', 'banner', 'expandable', 'interstitial', 'cpm') THEN 'Display' WHEN REGEXP_CONTAINS(source,'alibaba|amazon|google shopping|shopify|etsy|ebay|stripe|walmart') OR REGEXP_CONTAINS(campaign, '^(.*(([^a-df-z]|^)shop|shopping).*)$') THEN 'Organic Shopping' WHEN REGEXP_CONTAINS(source,'badoo|facebook|fb|instagram|linkedin|pinterest|tiktok|twitter|whatsapp') OR medium IN ('social','social-network','social-media','sm','social network','social media') THEN 'Organic Social' WHEN REGEXP_CONTAINS(source,'dailymotion|disneyplus|netflix|youtube|vimeo|twitch|vimeo|youtube') OR REGEXP_CONTAINS(medium,'^(.*video.*)$') THEN 'Organic Video' WHEN REGEXP_CONTAINS(source,'baidu|bing|duckduckgo|ecosia|google|yahoo|yandex') OR medium = 'organic' THEN 'Organic Search' WHEN REGEXP_CONTAINS(source,'email|e-mail|e_mail|e mail') OR REGEXP_CONTAINS(medium,'email|e-mail|e_mail|e mail') THEN 'Email' WHEN medium = 'affiliate' THEN 'Affiliates' WHEN medium = 'referral' THEN 'Referral' WHEN medium = 'audio' THEN 'Audio' WHEN medium = 'sms' THEN 'SMS' WHEN medium LIKE '%push' OR REGEXP_CONTAINS(medium,'mobile|notification') THEN 'Mobile Push Notifications' ELSE 'Unassigned' END AS channel_grouping_session FROM prep GROUP BY channel_grouping_session ORDER BY COUNT(DISTINCT CONCAT(user_pseudo_id, session_id)) DESC LIMIT 1 OFFSET 3",lite,ga010,events_*.event_params; events_*.event_timestamp; events_*.user_pseudo_id,3,23,True,ok,False,ga010 sf_ga012,GA4,bigquery,"On November 30, 2020, identify the item category with the highest tax rate by dividing tax value in usd by purchase revenue in usd for purchase events, and then retrieve the transaction IDs, total item quantities, and both purchase revenue in usd and purchase revenue for those purchase events in that top-tax-rate category.","WITH top_category AS ( SELECT product.item_category, SUM(ecommerce.tax_value_in_usd) / SUM(ecommerce.purchase_revenue_in_usd) AS tax_rate FROM bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20201130, UNNEST(items) AS product WHERE event_name = 'purchase' GROUP BY product.item_category ORDER BY tax_rate DESC LIMIT 1 ) SELECT ecommerce.transaction_id, SUM(ecommerce.total_item_quantity) AS total_item_quantity, SUM(ecommerce.purchase_revenue_in_usd) AS purchase_revenue_in_usd, SUM(ecommerce.purchase_revenue) AS purchase_revenue FROM bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_20201130, UNNEST(items) AS product JOIN top_category ON product.item_category = top_category.item_category WHERE event_name = 'purchase' GROUP BY ecommerce.transaction_id;",lite,ga012,events_*.ecommerce; events_*.event_name; events_*.items,3,23,True,ok,False,ga012 sf_ga017,GA4,bigquery,How many distinct users viewed the most frequently visited page during January 2021?,"WITH unnested_events AS ( SELECT MAX(CASE WHEN event_params.key = 'page_location' THEN event_params.value.string_value END) AS page_location, user_pseudo_id, event_timestamp FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`, UNNEST(event_params) AS event_params WHERE _TABLE_SUFFIX BETWEEN '20210101' AND '20210131' AND event_name = 'page_view' GROUP BY user_pseudo_id,event_timestamp ), temp AS ( SELECT page_location, COUNT(*) AS event_count, COUNT(DISTINCT user_pseudo_id) AS users FROM unnested_events GROUP BY page_location ORDER BY event_count DESC ) SELECT users FROM temp LIMIT 1",lite,ga017,events_*.event_name; events_*.event_params; events_*.event_timestamp; events_*.user_pseudo_id,4,23,True,ok,False,ga017 sf_ga018,GA4,bigquery,"On January 2nd, 2021, I want to determine the percentage of times users transition from a product list page (PLP) view to a product detail page (PDP) view within the same session, using only page_view events. Could you calculate how many PLP views eventually led to a PDP view in the same session on that date, and then provide the resulting percentage of PLP-to-PDP transitions?","WITH base_table AS ( SELECT event_name, event_date, event_timestamp, user_pseudo_id, user_id, device, geo, traffic_source, event_params, user_properties FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*` WHERE _table_suffix = '20210102' AND event_name IN ('page_view') ) , unnested_events AS ( -- unnests event parameters to get to relevant keys and values SELECT event_date AS date, event_timestamp AS event_timestamp_microseconds, user_pseudo_id, MAX(CASE WHEN c.key = 'ga_session_id' THEN c.value.int_value END) AS visitID, MAX(CASE WHEN c.key = 'ga_session_number' THEN c.value.int_value END) AS visitNumber, MAX(CASE WHEN c.key = 'page_title' THEN c.value.string_value END) AS page_title, MAX(CASE WHEN c.key = 'page_location' THEN c.value.string_value END) AS page_location FROM base_table, UNNEST (event_params) c GROUP BY 1,2,3 ) , unnested_events_categorised AS ( -- categorizing Page Titles into PDPs and PLPs SELECT *, CASE WHEN ARRAY_LENGTH(SPLIT(page_location, '/')) >= 5 AND CONTAINS_SUBSTR(ARRAY_REVERSE(SPLIT(page_location, '/'))[SAFE_OFFSET(0)], '+') AND (LOWER(SPLIT(page_location, '/')[SAFE_OFFSET(4)]) IN ('accessories','apparel','brands','campus+collection','drinkware', 'electronics','google+redesign', 'lifestyle','nest','new+2015+logo','notebooks+journals', 'office','shop+by+brand','small+goods','stationery','wearables' ) OR LOWER(SPLIT(page_location, '/')[SAFE_OFFSET(3)]) IN ('accessories','apparel','brands','campus+collection','drinkware', 'electronics','google+redesign', 'lifestyle','nest','new+2015+logo','notebooks+journals', 'office','shop+by+brand','small+goods','stationery','wearables' ) ) THEN 'PDP' WHEN NOT(CONTAINS_SUBSTR(ARRAY_REVERSE(SPLIT(page_location, '/'))[SAFE_OFFSET(0)], '+')) AND (LOWER(SPLIT(page_location, '/')[SAFE_OFFSET(4)]) IN ('accessories','apparel','brands','campus+collection','drinkware', 'electronics','google+redesign', 'lifestyle','nest','new+2015+logo','notebooks+journals', 'office','shop+by+brand','small+goods','stationery','wearables' ) OR LOWER(SPLIT(page_location, '/')[SAFE_OFFSET(3)]) IN ('accessories','apparel','brands','campus+collection','drinkware', 'electronics','google+redesign', 'lifestyle','nest','new+2015+logo','notebooks+journals', 'office','shop+by+brand','small+goods','stationery','wearables' ) ) THEN 'PLP' ELSE page_title END AS page_title_adjusted FROM unnested_events ) , ranked_screens AS ( SELECT *, LAG(page_title_adjusted,1) OVER (PARTITION BY user_pseudo_id, visitID ORDER BY event_timestamp_microseconds ASC) previous_page, LEAD(page_title_adjusted,1) OVER (PARTITION BY user_pseudo_id, visitID ORDER BY event_timestamp_microseconds ASC) next_page FROM unnested_events_categorised ) ,PLPtoPDPTransitions AS ( SELECT user_pseudo_id, visitID FROM ranked_screens WHERE page_title_adjusted = 'PLP' AND next_page = 'PDP' ) ,TotalPLPViews AS ( SELECT COUNT(*) AS total_plp_views FROM ranked_screens WHERE page_title_adjusted = 'PLP' ) ,TotalTransitions AS ( SELECT COUNT(*) AS total_transitions FROM PLPtoPDPTransitions ) SELECT (total_transitions * 100.0) / total_plp_views AS percentage FROM TotalTransitions, TotalPLPViews;",lite,ga018,events_*.event_date; events_*.event_name; events_*.event_params; events_*.event_timestamp; events_*.user_pseudo_id,5,23,True,fix,True,ga018 sf_ga019,FIREBASE,bigquery,Could you determine what percentage of users either did not uninstall our app within seven days or never uninstalled it after installing during August and September 2018?,"WITH --List of users who installed sept_cohort AS ( SELECT DISTINCT user_pseudo_id, FORMAT_DATE('%Y-%m-%d', PARSE_DATE('%Y%m%d', event_date)) AS date_first_open, FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name = 'first_open' AND _TABLE_SUFFIX BETWEEN '20180801' and '20180930' ), --Get the list of users who uninstalled uninstallers AS ( SELECT DISTINCT user_pseudo_id, FORMAT_DATE('%Y-%m-%d', PARSE_DATE('%Y%m%d', event_date)) AS date_app_remove, FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name = 'app_remove' AND _TABLE_SUFFIX BETWEEN '20180801' and '20180930' ), --Join the 2 tables and compute for # of days to uninstall joined AS ( SELECT a.*, b.date_app_remove, DATE_DIFF(DATE(b.date_app_remove), DATE(a.date_first_open), DAY) AS days_to_uninstall FROM sept_cohort a LEFT JOIN uninstallers b ON a.user_pseudo_id = b.user_pseudo_id ) --Compute for the percentage SELECT COUNT(DISTINCT CASE WHEN days_to_uninstall > 7 OR days_to_uninstall IS NULL THEN user_pseudo_id END) / COUNT(DISTINCT user_pseudo_id) AS percent_users_7_days FROM joined ",lite,ga019,events_*.event_date; events_*.event_name; events_*.user_pseudo_id,3,20,True,ok,False,ga019 sf_ga020,FIREBASE,bigquery,"Which quickplay event type had the lowest user retention rate during the second week after their initial engagement, for users who first engaged between August 1 and August 15, 2018, as measured by the presence of session_start events??","-- Define the date range and calculate the minimum date for filtering results WITH dates AS ( SELECT DATE('2018-08-01') AS start_date, DATE('2018-08-15') AS end_date ), -- Create a table of active dates for each user within the specified date range dates_active_table AS ( SELECT user_pseudo_id, PARSE_DATE('%Y%m%d', `event_date`) AS user_active_date FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name = 'session_start' AND PARSE_DATE('%Y%m%d', `event_date`) BETWEEN (SELECT start_date FROM dates) AND (SELECT end_date FROM dates) GROUP BY user_pseudo_id, user_active_date ), -- Create a table of the earliest quickplay event date for each user within the specified date range event_table AS ( SELECT user_pseudo_id, event_name, MIN(PARSE_DATE('%Y%m%d', `event_date`)) AS event_cohort_date FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name IN ('level_start_quickplay', 'level_end_quickplay', 'level_complete_quickplay', 'level_fail_quickplay', 'level_reset_quickplay', 'level_retry_quickplay') AND PARSE_DATE('%Y%m%d', `event_date`) BETWEEN (SELECT start_date FROM dates) AND (SELECT end_date FROM dates) GROUP BY user_pseudo_id, event_name ), -- Calculate the number of days since each user's initial quickplay event days_since_event_table AS ( SELECT events.user_pseudo_id, events.event_name AS event_cohort, events.event_cohort_date, days.user_active_date, DATE_DIFF(days.user_active_date, events.event_cohort_date, DAY) AS days_since_event FROM event_table events LEFT JOIN dates_active_table days ON events.user_pseudo_id = days.user_pseudo_id WHERE events.event_cohort_date <= days.user_active_date ), -- Calculate the weeks since each user's initial quickplay event and count the active days in each week weeks_retention AS ( SELECT event_cohort, user_pseudo_id, CAST(CASE WHEN days_since_event = 0 THEN 0 ELSE CEIL(days_since_event / 7) END AS INTEGER) AS weeks_since_event, COUNT(DISTINCT days_since_event) AS days_active_since_event -- Count Days Active in Week FROM days_since_event_table GROUP BY event_cohort, user_pseudo_id, weeks_since_event ), -- Aggregate the weekly retention data aggregated_weekly_retention_table AS ( SELECT event_cohort, weeks_since_event, SUM(days_active_since_event) AS weekly_days_active, COUNT(DISTINCT user_pseudo_id) AS retained_users FROM weeks_retention GROUP BY event_cohort, weeks_since_event ), RETENTION_INFO AS ( -- Select and calculate the weekly retention rate for each event cohort SELECT event_cohort, weeks_since_event, weekly_days_active, retained_users, (retained_users / MAX(retained_users) OVER (PARTITION BY event_cohort)) AS retention_rate FROM aggregated_weekly_retention_table ORDER BY event_cohort, weeks_since_event ) SELECT event_cohort FROM RETENTION_INFO WHERE weeks_since_event = 2 ORDER BY retention_rate LIMIT 1",lite,ga020,events_*.event_date; events_*.event_name; events_*.user_pseudo_id,3,20,True,ok,False,ga020 sf_ga021,FIREBASE,bigquery,"What is the retention rate for users two weeks after their initial quickplay event, calculated separately for each quickplay event type, within the period from July 2, 2018, to July 16, 2018? Please focus on users who started a session (session_start) during this period.","-- Define the date range and calculate the minimum date for filtering results WITH dates AS ( SELECT DATE('2018-07-02') AS start_date, DATE('2018-07-16') AS end_date ), -- Create a table of active dates for each user within the specified date range dates_active_table AS ( SELECT user_pseudo_id, PARSE_DATE('%Y%m%d', `event_date`) AS user_active_date FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name = 'session_start' AND PARSE_DATE('%Y%m%d', `event_date`) BETWEEN (SELECT start_date FROM dates) AND (SELECT end_date FROM dates) GROUP BY user_pseudo_id, user_active_date ), -- Create a table of the earliest quickplay event date for each user within the specified date range event_table AS ( SELECT user_pseudo_id, event_name, MIN(PARSE_DATE('%Y%m%d', `event_date`)) AS event_cohort_date FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name IN ('level_start_quickplay', 'level_end_quickplay', 'level_complete_quickplay', 'level_fail_quickplay', 'level_reset_quickplay', 'level_retry_quickplay') AND PARSE_DATE('%Y%m%d', `event_date`) BETWEEN (SELECT start_date FROM dates) AND (SELECT end_date FROM dates) GROUP BY user_pseudo_id, event_name ), -- Calculate the number of days since each user's initial quickplay event days_since_event_table AS ( SELECT events.user_pseudo_id, events.event_name AS event_cohort, events.event_cohort_date, days.user_active_date, DATE_DIFF(days.user_active_date, events.event_cohort_date, DAY) AS days_since_event FROM event_table events LEFT JOIN dates_active_table days ON events.user_pseudo_id = days.user_pseudo_id WHERE events.event_cohort_date <= days.user_active_date ), -- Calculate the weeks since each user's initial quickplay event and count the active days in each week weeks_retention AS ( SELECT event_cohort, user_pseudo_id, CAST(CASE WHEN days_since_event = 0 THEN 0 ELSE CEIL(days_since_event / 7) END AS INTEGER) AS weeks_since_event, COUNT(DISTINCT days_since_event) AS days_active_since_event -- Count Days Active in Week FROM days_since_event_table GROUP BY event_cohort, user_pseudo_id, weeks_since_event ), -- Aggregate the weekly retention data aggregated_weekly_retention_table AS ( SELECT event_cohort, weeks_since_event, SUM(days_active_since_event) AS weekly_days_active, COUNT(DISTINCT user_pseudo_id) AS retained_users FROM weeks_retention GROUP BY event_cohort, weeks_since_event ), RETENTION_INFO AS ( SELECT event_cohort, weeks_since_event, weekly_days_active, retained_users, (retained_users / MAX(retained_users) OVER (PARTITION BY event_cohort)) AS retention_rate FROM aggregated_weekly_retention_table ORDER BY event_cohort, weeks_since_event ) SELECT event_cohort, retention_rate FROM RETENTION_INFO WHERE weeks_since_event = 2",lite,ga021,events_*.event_date; events_*.event_name; events_*.user_pseudo_id,3,20,True,ok,False,ga021 sf_ga022,FIREBASE,bigquery,"Could you please help me get the weekly customer retention rate in September 2018 for new customers who first used our app (first_open event) within the first week starting from September 1st, 2018 (timezone in Shanghai)? The retention rates should cover the following weeks 1, 2, and 3 period after the initial use and display them in column format.","WITH analytics_data AS ( SELECT user_pseudo_id, event_timestamp, event_name, UNIX_MICROS(TIMESTAMP(""2018-09-01 00:00:00"", ""+8:00"")) AS start_day, 3600*1000*1000*24*7 AS one_week_micros FROM `firebase-public-project.analytics_153293282.events_*` WHERE _table_suffix BETWEEN '20180901' AND '20180930' ) SELECT week_1_cohort / week_0_cohort AS week_1_pct, week_2_cohort / week_0_cohort AS week_2_pct, week_3_cohort / week_0_cohort AS week_3_pct FROM ( WITH week_3_users AS ( SELECT DISTINCT user_pseudo_id FROM analytics_data WHERE event_timestamp BETWEEN start_day+(3*one_week_micros) AND start_day+(4*one_week_micros) ), week_2_users AS ( SELECT DISTINCT user_pseudo_id FROM analytics_data WHERE event_timestamp BETWEEN start_day+(2*one_week_micros) AND start_day+(3*one_week_micros) ), week_1_users AS ( SELECT DISTINCT user_pseudo_id FROM analytics_data WHERE event_timestamp BETWEEN start_day+(1*one_week_micros) AND start_day+(2*one_week_micros) ), week_0_users AS ( SELECT DISTINCT user_pseudo_id FROM analytics_data WHERE event_name = 'first_open' AND event_timestamp BETWEEN start_day AND start_day+(1*one_week_micros) ) SELECT (SELECT count(*) FROM week_0_users) AS week_0_cohort, (SELECT count(*) FROM week_1_users JOIN week_0_users USING (user_pseudo_id)) AS week_1_cohort, (SELECT count(*) FROM week_2_users JOIN week_0_users USING (user_pseudo_id)) AS week_2_cohort, (SELECT count(*) FROM week_3_users JOIN week_0_users USING (user_pseudo_id)) AS week_3_cohort )",lite,ga022,events_*.event_name; events_*.event_timestamp; events_*.user_pseudo_id,3,20,True,ok,False,ga022 sf_ga028,FIREBASE,bigquery,"Please perform a 7-day retention analysis for users who first session start the app during the week starting on July 2, 2018. For each week from Week 0 (the week of their first session) to Week 4, provide the total number of new users in Week 0 and the number of retained users for each subsequent week. Ensuring that you only count events up to October 2, 2018, and group dates by Monday-based weeks","WITH dates AS ( SELECT DATE('2018-07-02') AS start_date, DATE('2018-10-02') AS end_date, DATE_ADD(DATE_TRUNC(DATE('2018-10-02'), WEEK(TUESDAY)), INTERVAL -4 WEEK) AS min_date ), date_table AS ( SELECT DISTINCT PARSE_DATE('%Y%m%d', `event_date`) AS event_date, user_pseudo_id, CASE WHEN DATE_DIFF(PARSE_DATE('%Y%m%d', `event_date`), DATE(TIMESTAMP_MICROS(user_first_touch_timestamp)), DAY) = 0 THEN 1 ELSE 0 END AS is_new_user FROM `firebase-public-project.analytics_153293282.events_*` WHERE event_name = 'session_start' ), new_user_list AS ( SELECT DISTINCT user_pseudo_id, event_date FROM date_table WHERE is_new_user = 1 ), days_since_start_table AS ( SELECT DISTINCT is_new_user, nu.event_date AS date_cohort, dt.user_pseudo_id, dt.event_date, DATE_DIFF(dt.event_date, nu.event_date, DAY) AS days_since_start FROM date_table dt JOIN new_user_list nu ON dt.user_pseudo_id = nu.user_pseudo_id ), weeks_retention AS ( SELECT date_cohort, DATE_TRUNC(date_cohort, WEEK(MONDAY)) AS week_cohort, user_pseudo_id, days_since_start, CASE WHEN days_since_start = 0 THEN 0 ELSE CEIL(days_since_start / 7) END AS weeks_since_start FROM days_since_start_table ), RETENTION_INFO AS ( SELECT week_cohort, weeks_since_start, COUNT(DISTINCT user_pseudo_id) AS retained_users FROM weeks_retention WHERE week_cohort <= (SELECT min_date FROM dates) GROUP BY week_cohort, weeks_since_start HAVING weeks_since_start <= 4 ORDER BY week_cohort, weeks_since_start ) SELECT weeks_since_start, retained_users FROM RETENTION_INFO WHERE week_cohort = DATE('2018-07-02') ",lite,ga028,events_*.event_date; events_*.event_name; events_*.user_first_touch_timestamp; events_*.user_pseudo_id,4,20,True,ok,False,ga028 sf_local003,E_COMMERCE,snowflake,"According to the RFM definition document, calculate the average sales per order for each customer within distinct RFM segments, considering only 'delivered' orders. Use the customer unique identifier. Clearly define how to calculate Recency based on the latest purchase timestamp and specify the criteria for classifying RFM segments. The average sales should be computed as the total spend divided by the total number of orders. Please analyze and report the differences in average sales across the RFM segments","WITH CustomerOrderStats AS ( SELECT C.""customer_unique_id"", O.""order_id"", TO_TIMESTAMP(O.""order_purchase_timestamp"") AS ""order_purchase_timestamp"", P.""payment_value"" FROM ""E_COMMERCE"".""E_COMMERCE"".""CUSTOMERS"" AS C JOIN ""E_COMMERCE"".""E_COMMERCE"".""ORDERS"" AS O ON C.""customer_id"" = O.""customer_id"" JOIN ""E_COMMERCE"".""E_COMMERCE"".""ORDER_PAYMENTS"" AS P ON O.""order_id"" = P.""order_id"" WHERE O.""order_status"" = 'delivered' ), MaxDate AS ( SELECT MAX(""order_purchase_timestamp"") AS ""max_purchase_date"" FROM CustomerOrderStats ), RFM_Base AS ( SELECT ""customer_unique_id"", DATEDIFF(day, MAX(""order_purchase_timestamp""), (SELECT ""max_purchase_date"" FROM MaxDate)) AS ""Recency"", COUNT(DISTINCT ""order_id"") AS ""Frequency"", SUM(""payment_value"") AS ""Monetary"", COUNT(DISTINCT ""order_id"") AS ""TotalOrders"", SUM(""payment_value"") AS ""TotalSpend"" FROM CustomerOrderStats GROUP BY ""customer_unique_id"" ), RFM_Scores AS ( SELECT *, NTILE(5) OVER (ORDER BY ""Recency"" ASC) AS ""R"", NTILE(5) OVER (ORDER BY ""Frequency"" DESC) AS ""F"", NTILE(5) OVER (ORDER BY ""Monetary"" DESC) AS ""M"" FROM RFM_Base ), RFM_Segments AS ( SELECT *, CASE WHEN ""R"" = 1 AND (""F"" + ""M"") BETWEEN 1 AND 4 THEN 'Champions' WHEN (""R"" = 4 OR ""R"" = 5) AND (""F"" + ""M"") BETWEEN 1 AND 2 THEN 'Can''t Lose Them' WHEN (""R"" = 4 OR ""R"" = 5) AND (""F"" + ""M"") BETWEEN 3 AND 6 THEN 'Hibernating' WHEN (""R"" = 4 OR ""R"" = 5) AND (""F"" + ""M"") BETWEEN 7 AND 10 THEN 'Lost' WHEN (""R"" = 2 OR ""R"" = 3) AND (""F"" + ""M"") BETWEEN 1 AND 4 THEN 'Loyal Customers' WHEN ""R"" = 3 AND (""F"" + ""M"") BETWEEN 5 AND 6 THEN 'Needs Attention' WHEN ""R"" = 1 AND (""F"" + ""M"") BETWEEN 7 AND 8 THEN 'Recent Users' WHEN (""R"" = 1 AND (""F"" + ""M"") BETWEEN 5 AND 6) OR (""R"" = 2 AND (""F"" + ""M"") BETWEEN 5 AND 8) THEN 'Potential Loyalists' WHEN ""R"" = 1 AND (""F"" + ""M"") BETWEEN 9 AND 10 THEN 'Price Sensitive' WHEN ""R"" = 2 AND (""F"" + ""M"") BETWEEN 9 AND 10 THEN 'Promising' WHEN ""R"" = 3 AND (""F"" + ""M"") BETWEEN 7 AND 10 THEN 'About to Sleep' ELSE 'Others' END AS ""RFM_Segment"" FROM RFM_Scores ) SELECT ""RFM_Segment"", SUM(""TotalSpend"") / SUM(""TotalOrders"") AS ""AverageSalesPerOrder"" FROM RFM_Segments GROUP BY ""RFM_Segment"" ORDER BY ""AverageSalesPerOrder"" DESC",snow,sf_local003,customers.customer_id; customers.customer_unique_id; order_payments.order_id; order_payments.payment_value; orders.customer_id; orders.order_id; orders.order_purchase_timestamp; orders.order_status,8,70,True,ok,False,local003 sf_local004,E_COMMERCE,snowflake,"Could you tell me the number of orders, average payment per order and customer lifespan in weeks of the 3 custumers with the highest average payment per order, where the lifespan is calculated by subtracting the earliest purchase date from the latest purchase date in days, dividing by seven, and if the result is less than seven days, setting it to 1.0?","WITH OrderTotalPayments AS ( SELECT ""order_id"", SUM(""payment_value"") AS ""total_payment"" FROM ""E_COMMERCE"".""E_COMMERCE"".""ORDER_PAYMENTS"" GROUP BY ""order_id"" ) SELECT C.""customer_unique_id"", COUNT(O.""order_id"") AS ""number_of_orders"", AVG(OTP.""total_payment"") AS ""average_payment_per_order"", CASE WHEN DATEDIFF('day', MIN(TO_TIMESTAMP(O.""order_purchase_timestamp"")), MAX(TO_TIMESTAMP(O.""order_purchase_timestamp""))) < 7 THEN 1.0 ELSE DATEDIFF('day', MIN(TO_TIMESTAMP(O.""order_purchase_timestamp"")), MAX(TO_TIMESTAMP(O.""order_purchase_timestamp""))) / 7.0 END AS ""customer_lifespan_in_weeks"" FROM ""E_COMMERCE"".""E_COMMERCE"".""CUSTOMERS"" AS C JOIN ""E_COMMERCE"".""E_COMMERCE"".""ORDERS"" AS O ON C.""customer_id"" = O.""customer_id"" JOIN OrderTotalPayments AS OTP ON O.""order_id"" = OTP.""order_id"" GROUP BY C.""customer_unique_id"" ORDER BY ""average_payment_per_order"" DESC LIMIT 3;",snow,sf_local004,customers.customer_id; customers.customer_unique_id; order_payments.order_id; order_payments.payment_value; orders.customer_id; orders.order_id; orders.order_purchase_timestamp,7,70,True,ok,False,local004 sf_local008,BASEBALL,duckdb,"I would like to know the given names of baseball players who have achieved the highest value of games played, runs, hits, and home runs, with their corresponding score values.","WITH player_stats AS ( SELECT b.player_id, p.name_given AS player_name, SUM(b.g) AS games_played, SUM(b.r) AS runs, SUM(b.h) AS hits, SUM(b.hr) AS home_runs FROM player p JOIN batting b ON p.player_id = b.player_id GROUP BY b.player_id, p.name_given ) SELECT 'Games Played' AS Category, player_name AS Player_Name, games_played AS Batting_Table_Topper FROM player_stats WHERE games_played = (SELECT MAX(games_played) FROM player_stats) UNION ALL SELECT 'Runs' AS Category, player_name AS Player_Name, runs AS Batting_Table_Topper FROM player_stats WHERE runs = (SELECT MAX(runs) FROM player_stats) UNION ALL SELECT 'Hits' AS Category, player_name AS Player_Name, hits AS Batting_Table_Topper FROM player_stats WHERE hits = (SELECT MAX(hits) FROM player_stats) UNION ALL SELECT 'Home Runs' AS Category, player_name AS Player_Name, home_runs AS Batting_Table_Topper FROM player_stats WHERE home_runs = (SELECT MAX(home_runs) FROM player_stats); ",lite,local008,batting.g; batting.h; batting.hr; batting.player_id; batting.r; player.name_given; player.player_id,7,46,True,ok,False,local008 sf_local017,CALIFORNIA_TRAFFIC_COLLISION,duckdb,In which year were the two most common causes of traffic accidents different from those in other years?,"WITH AnnualTotals AS ( SELECT STRFTIME('%Y', collision_date) AS Year, COUNT(case_id) AS AnnualTotal FROM collisions GROUP BY Year ), CategoryTotals AS ( SELECT STRFTIME('%Y', collision_date) AS Year, pcf_violation_category AS Category, COUNT(case_id) AS Subtotal FROM collisions GROUP BY Year, Category ), CategoryPercentages AS ( SELECT ct.Year, ct.Category, ROUND((ct.Subtotal * 100.0) / at.AnnualTotal, 1) AS PercentageOfAnnualRoadIncidents FROM CategoryTotals ct JOIN AnnualTotals at ON ct.Year = at.Year ), RankedCategories AS ( SELECT Year, Category, PercentageOfAnnualRoadIncidents, ROW_NUMBER() OVER (PARTITION BY Year ORDER BY PercentageOfAnnualRoadIncidents DESC) AS Rank FROM CategoryPercentages ), TopTwoCategories AS ( SELECT Year, GROUP_CONCAT(Category, ', ') AS TopCategories FROM RankedCategories WHERE Rank <= 2 GROUP BY Year ), UniqueYear AS ( SELECT Year FROM TopTwoCategories GROUP BY TopCategories HAVING COUNT(Year) = 1 ), results AS ( SELECT rc.Year, rc.Category, rc.PercentageOfAnnualRoadIncidents FROM UniqueYear u JOIN RankedCategories rc ON u.Year = rc.Year WHERE rc.Rank <= 2 ) SELECT distinct Year FROM results",lite,local017,collisions.case_id; collisions.collision_date; collisions.pcf_violation_category,3,120,True,ok,False,local017 sf_local019,WWE,snowflake,"For the NXT title that had the shortest match (excluding titles with ""title change""), what were the names of the two wrestlers involved?","SELECT w1.""name"" as wrestler1, w2.""name"" as wrestler2 FROM WWE.WWE.MATCHES m JOIN WWE.WWE.WRESTLERS w1 ON m.""winner_id"" = w1.""id""::VARCHAR JOIN WWE.WWE.WRESTLERS w2 ON m.""loser_id"" = w2.""id""::VARCHAR WHERE m.""title_id"" IN (SELECT ""id""::VARCHAR FROM WWE.WWE.BELTS WHERE ""name"" LIKE '%NXT%') AND m.""title_change"" = 0 AND m.""duration"" IS NOT NULL AND m.""duration"" != '' ORDER BY m.""duration"" ASC LIMIT 1",snow,sf_local019,belts.id; belts.name; matches.duration; matches.loser_id; matches.title_change; matches.title_id; matches.winner_id; wrestlers.id; wrestlers.name,9,33,True,fix,True,local019 sf_local022,IPL,snowflake,Retrieve the names of players who scored no less than 100 runs in a match while playing for the team that lost that match.,"with ""PLAYER_RUNS"" as ( select ""B"".""match_id"", ""B"".""striker"" as ""player_id"", sum(""BS"".""runs_scored"") as ""runs"" from ""IPL"".""IPL"".""BALL_BY_BALL"" ""B"" join ""IPL"".""IPL"".""BATSMAN_SCORED"" ""BS"" on ""B"".""match_id"" = ""BS"".""match_id"" and ""B"".""over_id"" = ""BS"".""over_id"" and ""B"".""ball_id"" = ""BS"".""ball_id"" and ""B"".""innings_no"" = ""BS"".""innings_no"" group by ""B"".""match_id"", ""B"".""striker"" ) select distinct ""P"".""player_name"" from ""PLAYER_RUNS"" ""PR"" join ""IPL"".""IPL"".""PLAYER_MATCH"" ""PM"" on ""PM"".""match_id"" = ""PR"".""match_id"" and ""PM"".""player_id"" = ""PR"".""player_id"" join ""IPL"".""IPL"".""MATCH"" ""M"" on ""M"".""match_id"" = ""PR"".""match_id"" join ""IPL"".""IPL"".""PLAYER"" ""P"" on ""P"".""player_id"" = ""PR"".""player_id"" where ""PR"".""runs"" >= 100 and ""M"".""match_winner"" is not null and ""PM"".""team_id"" in (""M"".""team_1"", ""M"".""team_2"") and ""PM"".""team_id"" != ""M"".""match_winner""",snow,sf_local022,ball_by_ball.ball_id; ball_by_ball.innings_no; ball_by_ball.match_id; ball_by_ball.over_id; ball_by_ball.striker; batsman_scored.ball_id; batsman_scored.innings_no; batsman_scored.match_id; batsman_scored.over_id; batsman_scored.runs_scored; match.match_id; match.match_winner; match.team_1; match.team_2; player.player_id; player.player_name; player_match.match_id; player_match.player_id; player_match.team_id,19,52,True,ok,False,local022 sf_local023,IPL,duckdb,"Please help me find the names of top 5 players with the highest average runs per match in season 5, along with their batting averages.","WITH runs_scored AS ( SELECT bb.striker AS player_id, bb.match_id, bs.runs_scored AS runs FROM ball_by_ball AS bb JOIN batsman_scored AS bs ON bb.match_id = bs.match_id AND bb.over_id = bs.over_id AND bb.ball_id = bs.ball_id AND bb.innings_no = bs.innings_no WHERE bb.match_id IN (SELECT match_id FROM match WHERE season_id = 5) ), total_runs AS ( SELECT player_id, match_id, SUM(runs) AS total_runs FROM runs_scored GROUP BY player_id, match_id ), batting_averages AS ( SELECT player_id, SUM(total_runs) AS runs, COUNT(match_id) AS num_matches, ROUND(SUM(total_runs) / CAST(COUNT(match_id) AS FLOAT), 3) AS batting_avg FROM total_runs GROUP BY player_id ORDER BY batting_avg DESC LIMIT 5 ) SELECT p.player_name, b.batting_avg FROM player AS p JOIN batting_averages AS b ON p.player_id = b.player_id ORDER BY b.batting_avg DESC;",lite,local023,ball_by_ball.ball_id; ball_by_ball.innings_no; ball_by_ball.match_id; ball_by_ball.over_id; ball_by_ball.striker; batsman_scored.ball_id; batsman_scored.innings_no; batsman_scored.match_id; batsman_scored.over_id; batsman_scored.runs_scored; match.match_id; match.season_id; player.player_id; player.player_name,14,52,True,ok,False,local023 sf_local029,BRAZILIAN_E_COMMERCE,duckdb,"Please identify the top three customers, based on their customer_unique_id, who have the highest number of delivered orders, and provide the average payment value, city, and state for each of these customers.","WITH customer_orders AS ( SELECT c.customer_unique_id, COUNT(o.order_id) AS Total_Orders_By_Customers, AVG(p.payment_value) AS Average_Payment_By_Customer, c.customer_city, c.customer_state FROM olist_customers c JOIN olist_orders o ON c.customer_id = o.customer_id JOIN olist_order_payments p ON o.order_id = p.order_id WHERE o.order_status = 'delivered' GROUP BY c.customer_unique_id, c.customer_city, c.customer_state ) SELECT Average_Payment_By_Customer, customer_city, customer_state FROM customer_orders ORDER BY Total_Orders_By_Customers DESC LIMIT 3;",lite,local029,olist_customers.customer_city; olist_customers.customer_id; olist_customers.customer_state; olist_customers.customer_unique_id; olist_order_payments.order_id; olist_order_payments.payment_value; olist_orders.customer_id; olist_orders.order_id; olist_orders.order_status,9,62,True,ok,False,local029 sf_local038,PAGILA,snowflake,"Could you help me determine which actor starred most frequently in English-language children's category films that were rated either G or PG, had a running time of 120 minutes or less, and were released between 2000 and 2010? Please provide the actor's full name.","SELECT CONCAT(""a"".""first_name"", ' ', ""a"".""last_name"") AS ""actor_full_name"" FROM ""PAGILA"".""PAGILA"".""FILM"" AS ""f"" JOIN ""PAGILA"".""PAGILA"".""LANGUAGE"" AS ""l"" ON ""f"".""language_id"" = ""l"".""language_id"" JOIN ""PAGILA"".""PAGILA"".""FILM_CATEGORY"" AS ""fc"" ON ""fc"".""film_id"" = ""f"".""film_id"" JOIN ""PAGILA"".""PAGILA"".""CATEGORY"" AS ""c"" ON ""c"".""category_id"" = ""fc"".""category_id"" JOIN ""PAGILA"".""PAGILA"".""FILM_ACTOR"" AS ""fa"" ON ""fa"".""film_id"" = ""f"".""film_id"" JOIN ""PAGILA"".""PAGILA"".""ACTOR"" AS ""a"" ON ""a"".""actor_id"" = ""fa"".""actor_id"" WHERE UPPER(""c"".""name"") = 'CHILDREN' AND UPPER(""l"".""name"") = 'ENGLISH' AND ""f"".""rating"" IN ('G', 'PG') AND ""f"".""length"" <= 120 AND TRY_TO_NUMBER(""f"".""release_year"") BETWEEN 2000 AND 2010 GROUP BY 1 ORDER BY COUNT(DISTINCT ""f"".""film_id"") DESC, ""actor_full_name"" LIMIT 1;",snow,sf_local038,actor.actor_id; actor.first_name; actor.last_name; category.category_id; category.name; film.film_id; film.language_id; film.length; film.rating; film.release_year; film_actor.actor_id; film_actor.film_id; film_category.category_id; film_category.film_id; language.language_id; language.name,16,89,True,ok,False,local038 sf_local039,PAGILA,snowflake,"Please help me find the film category with the highest total rental hours in cities where the city's name either starts with ""A"" or contains a hyphen. ","SELECT c.""name"" AS category_name, SUM(DATEDIFF('second', TRY_TO_TIMESTAMP_NTZ(r.""rental_date""), TRY_TO_TIMESTAMP_NTZ(r.""return_date"")))/3600.0 AS total_rental_hours FROM ""PAGILA"".""PAGILA"".""RENTAL"" r JOIN ""PAGILA"".""PAGILA"".""INVENTORY"" i ON r.""inventory_id"" = i.""inventory_id"" JOIN ""PAGILA"".""PAGILA"".""FILM_CATEGORY"" fc ON i.""film_id"" = fc.""film_id"" JOIN ""PAGILA"".""PAGILA"".""CATEGORY"" c ON fc.""category_id"" = c.""category_id"" JOIN ""PAGILA"".""PAGILA"".""CUSTOMER"" cu ON r.""customer_id"" = cu.""customer_id"" JOIN ""PAGILA"".""PAGILA"".""ADDRESS"" a ON cu.""address_id"" = a.""address_id"" JOIN ""PAGILA"".""PAGILA"".""CITY"" ci ON a.""city_id"" = ci.""city_id"" WHERE TRY_TO_TIMESTAMP_NTZ(r.""rental_date"") IS NOT NULL AND TRY_TO_TIMESTAMP_NTZ(r.""return_date"") IS NOT NULL AND (ci.""city"" ILIKE 'A%' OR ci.""city"" ILIKE '%-%') GROUP BY c.""category_id"", c.""name"" ORDER BY total_rental_hours DESC LIMIT 1;",snow,sf_local039,address.address_id; address.city_id; category.category_id; category.name; city.city; city.city_id; customer.address_id; customer.customer_id; film_category.category_id; film_category.film_id; inventory.film_id; inventory.inventory_id; rental.customer_id; rental.inventory_id; rental.rental_date; rental.return_date,16,89,True,ok,False,local039 sf_local058,EDUCATION_BUSINESS,duckdb,"Can you provide a list of hardware product segments along with their unique product counts for 2020 in the output, ordered by the highest percentage increase in unique fact sales products from 2020 to 2021?","WITH UniqueProducts2020 AS ( SELECT dp.segment, COUNT(DISTINCT fsm.product_code) AS unique_products_2020 FROM hardware_fact_sales_monthly fsm JOIN hardware_dim_product dp ON fsm.product_code = dp.product_code WHERE fsm.fiscal_year = 2020 GROUP BY dp.segment ), UniqueProducts2021 AS ( SELECT dp.segment, COUNT(DISTINCT fsm.product_code) AS unique_products_2021 FROM hardware_fact_sales_monthly fsm JOIN hardware_dim_product dp ON fsm.product_code = dp.product_code WHERE fsm.fiscal_year = 2021 GROUP BY dp.segment ) SELECT spc.segment, spc.unique_products_2020 AS product_count_2020 FROM UniqueProducts2020 spc JOIN UniqueProducts2021 fup ON spc.segment = fup.segment ORDER BY ((fup.unique_products_2021 - spc.unique_products_2020) * 100.0) / (spc.unique_products_2020) DESC; ",lite,local058,hardware_dim_product.product_code; hardware_dim_product.segment; hardware_fact_sales_monthly.fiscal_year; hardware_fact_sales_monthly.product_code,4,98,True,ok,False,local058 sf_local065,MODERN_DATA,duckdb,Calculate the total income from Meat Lovers pizzas priced at $12 and Vegetarian pizzas at $10. Include any extra toppings charged at $1 each. Ensure that canceled orders are filtered out. How much money has Pizza Runner earned in total?,"WITH get_extras_count AS ( WITH RECURSIVE split_extras AS ( SELECT order_id, TRIM(SUBSTR(extras, 1, INSTR(extras || ',', ',') - 1)) AS each_extra, SUBSTR(extras || ',', INSTR(extras || ',', ',') + 1) AS remaining_extras FROM pizza_clean_customer_orders UNION ALL SELECT order_id, TRIM(SUBSTR(remaining_extras, 1, INSTR(remaining_extras, ',') - 1)) AS each_extra, SUBSTR(remaining_extras, INSTR(remaining_extras, ',') + 1) FROM split_extras WHERE remaining_extras <> '' ) SELECT order_id, COUNT(each_extra) AS total_extras FROM split_extras GROUP BY order_id ), calculate_totals AS ( SELECT t1.order_id, t1.pizza_id, SUM( CASE WHEN pizza_id = 1 THEN 12 WHEN pizza_id = 2 THEN 10 END ) AS total_price, t3.total_extras FROM pizza_clean_customer_orders AS t1 JOIN pizza_clean_runner_orders AS t2 ON t2.order_id = t1.order_id LEFT JOIN get_extras_count AS t3 ON t3.order_id = t1.order_id WHERE t2.cancellation IS NULL GROUP BY t1.order_id, t1.pizza_id, t3.total_extras ) SELECT SUM(total_price) + SUM(total_extras) AS total_income FROM calculate_totals; ",lite,local065,pizza_clean_customer_orders.extras; pizza_clean_customer_orders.order_id; pizza_clean_customer_orders.pizza_id; pizza_clean_runner_orders.cancellation; pizza_clean_runner_orders.order_id,5,77,True,ok,False,local065 sf_local066,MODERN_DATA,duckdb,"Based on our customer pizza order information, summarize the total quantity of each ingredient used in the pizzas we delivered. Output the name and quantity for each ingredient.","WITH cte_cleaned_customer_orders AS ( SELECT *, ROW_NUMBER() OVER () AS original_row_number FROM pizza_clean_customer_orders ), split_regular_toppings AS ( SELECT pizza_id, TRIM(SUBSTR(toppings, 1, INSTR(toppings || ',', ',') - 1)) AS topping_id, SUBSTR(toppings || ',', INSTR(toppings || ',', ',') + 1) AS remaining_toppings FROM pizza_recipes UNION ALL SELECT pizza_id, TRIM(SUBSTR(remaining_toppings, 1, INSTR(remaining_toppings, ',') - 1)) AS topping_id, SUBSTR(remaining_toppings, INSTR(remaining_toppings, ',') + 1) AS remaining_toppings FROM split_regular_toppings WHERE remaining_toppings <> '' ), cte_base_toppings AS ( SELECT t1.order_id, t1.customer_id, t1.pizza_id, t1.order_time, t1.original_row_number, t2.topping_id FROM cte_cleaned_customer_orders AS t1 LEFT JOIN split_regular_toppings AS t2 ON t1.pizza_id = t2.pizza_id ), split_exclusions AS ( SELECT order_id, customer_id, pizza_id, order_time, original_row_number, TRIM(SUBSTR(exclusions, 1, INSTR(exclusions || ',', ',') - 1)) AS topping_id, SUBSTR(exclusions || ',', INSTR(exclusions || ',', ',') + 1) AS remaining_exclusions FROM cte_cleaned_customer_orders WHERE exclusions IS NOT NULL UNION ALL SELECT order_id, customer_id, pizza_id, order_time, original_row_number, TRIM(SUBSTR(remaining_exclusions, 1, INSTR(remaining_exclusions, ',') - 1)) AS topping_id, SUBSTR(remaining_exclusions, INSTR(remaining_exclusions, ',') + 1) AS remaining_exclusions FROM split_exclusions WHERE remaining_exclusions <> '' ), split_extras AS ( SELECT order_id, customer_id, pizza_id, order_time, original_row_number, TRIM(SUBSTR(extras, 1, INSTR(extras || ',', ',') - 1)) AS topping_id, SUBSTR(extras || ',', INSTR(extras || ',', ',') + 1) AS remaining_extras FROM cte_cleaned_customer_orders WHERE extras IS NOT NULL UNION ALL SELECT order_id, customer_id, pizza_id, order_time, original_row_number, TRIM(SUBSTR(remaining_extras, 1, INSTR(remaining_extras, ',') - 1)) AS topping_id, SUBSTR(remaining_extras, INSTR(remaining_extras, ',') + 1) AS remaining_extras FROM split_extras WHERE remaining_extras <> '' ), cte_combined_orders AS ( SELECT order_id, customer_id, pizza_id, order_time, original_row_number, topping_id FROM cte_base_toppings WHERE topping_id NOT IN (SELECT topping_id FROM split_exclusions WHERE split_exclusions.order_id = cte_base_toppings.order_id) UNION ALL SELECT order_id, customer_id, pizza_id, order_time, original_row_number, topping_id FROM split_extras ) SELECT t2.topping_name, COUNT(*) AS topping_count FROM cte_combined_orders AS t1 JOIN pizza_toppings AS t2 ON t1.topping_id = t2.topping_id GROUP BY t2.topping_name ORDER BY topping_count DESC; ",lite,local066,pizza_clean_customer_orders.customer_id; pizza_clean_customer_orders.exclusions; pizza_clean_customer_orders.extras; pizza_clean_customer_orders.order_id; pizza_clean_customer_orders.order_time; pizza_clean_customer_orders.pizza_id; pizza_recipes.pizza_id; pizza_recipes.toppings; pizza_toppings.topping_id; pizza_toppings.topping_name,10,77,True,ok,False,local066 sf_local075,BANK_SALES_TRADING,snowflake,"Can you provide a breakdown of how many times each product was viewed, how many times they were added to the shopping cart, and how many times they were left in the cart without being purchased? Also, give me the count of actual purchases for each product. Ensure that products with a page id in (1, 2, 12, 13) are filtered out.","WITH ""product_events"" AS ( SELECT p.""product_id"", p.""page_name"", p.""product_category"", e.""visit_id"", e.""event_type"", e.""sequence_number"" FROM ""BANK_SALES_TRADING"".""BANK_SALES_TRADING"".""SHOPPING_CART_EVENTS"" e JOIN ""BANK_SALES_TRADING"".""BANK_SALES_TRADING"".""SHOPPING_CART_PAGE_HIERARCHY"" p ON e.""page_id"" = p.""page_id"" WHERE p.""product_id"" IS NOT NULL AND p.""page_id"" NOT IN (1, 2, 12, 13) ), ""views_agg"" AS ( SELECT ""product_id"", ""page_name"", ""product_category"", COUNT(*) AS ""total_views"" FROM ""product_events"" WHERE ""event_type"" = 1 GROUP BY ""product_id"", ""page_name"", ""product_category"" ), ""adds"" AS ( SELECT ""product_id"", ""page_name"", ""product_category"", ""visit_id"", ""sequence_number"" AS ""add_seq"" FROM ""product_events"" WHERE ""event_type"" = 2 ), ""purchases"" AS ( SELECT ""visit_id"", ""sequence_number"" AS ""purchase_seq"" FROM ""BANK_SALES_TRADING"".""BANK_SALES_TRADING"".""SHOPPING_CART_EVENTS"" WHERE ""event_type"" = 3 ), ""add_outcomes"" AS ( SELECT a.""product_id"", a.""page_name"", a.""product_category"", a.""visit_id"", a.""add_seq"", CASE WHEN EXISTS ( SELECT 1 FROM ""purchases"" p WHERE p.""visit_id"" = a.""visit_id"" AND p.""purchase_seq"" > a.""add_seq"" ) THEN 1 ELSE 0 END AS ""purchased_flag"" FROM ""adds"" a ), ""add_agg"" AS ( SELECT ""product_id"", ""page_name"", ""product_category"", COUNT(*) AS ""total_adds_to_cart"", SUM(""purchased_flag"") AS ""total_purchases"", COUNT(*) - SUM(""purchased_flag"") AS ""left_in_cart_without_purchase"" FROM ""add_outcomes"" GROUP BY ""product_id"", ""page_name"", ""product_category"" ) SELECT v.""product_id"", v.""page_name"", v.""product_category"", v.""total_views"", COALESCE(a.""total_adds_to_cart"", 0) AS ""total_adds_to_cart"", COALESCE(a.""left_in_cart_without_purchase"", 0) AS ""left_in_cart_without_purchase"", COALESCE(a.""total_purchases"", 0) AS ""total_purchases"" FROM ""views_agg"" v LEFT JOIN ""add_agg"" a ON v.""product_id"" = a.""product_id"" AND v.""page_name"" = a.""page_name"" AND v.""product_category"" = a.""product_category"" ORDER BY v.""product_id"";",snow,sf_local075,shopping_cart_events.event_type; shopping_cart_events.page_id; shopping_cart_events.sequence_number; shopping_cart_events.visit_id; shopping_cart_page_hierarchy.page_id; shopping_cart_page_hierarchy.page_name; shopping_cart_page_hierarchy.product_category; shopping_cart_page_hierarchy.product_id,8,106,True,ok,False,local075 sf_local078,BANK_SALES_TRADING,duckdb,"Identify the top 10 and bottom 10 interest categories based on their highest composition values across all months. For each category, display the time(MM-YYYY), interest name, and the composition value","WITH get_interest_rank AS ( SELECT t1.month_year, t2.interest_name, t1.composition, RANK() OVER ( PARTITION BY t2.interest_name ORDER BY t1.composition DESC ) AS interest_rank FROM interest_metrics AS t1 JOIN interest_map AS t2 ON t1.interest_id = t2.id WHERE t1.month_year IS NOT NULL ), get_top_10 AS ( SELECT month_year, interest_name, composition FROM get_interest_rank WHERE interest_rank = 1 ORDER BY composition DESC LIMIT 10 ), get_bottom_10 AS ( SELECT month_year, interest_name, composition FROM get_interest_rank WHERE interest_rank = 1 ORDER BY composition ASC LIMIT 10 ) SELECT * FROM get_top_10 UNION SELECT * FROM get_bottom_10 ORDER BY composition DESC; ",lite,local078,interest_map.id; interest_map.interest_name; interest_metrics.composition; interest_metrics.interest_id; interest_metrics.month_year,5,106,True,ok,False,local078 sf_local099,DB_IMDB,duckdb,I need you to look into the actor collaborations and tell me how many actors have made more films with Yash Chopra than with any other director. This will help us understand his influence on the industry better.,"WITH YASH_CHOPRAS_PID AS ( SELECT TRIM(P.PID) AS PID FROM Person P WHERE TRIM(P.Name) = 'Yash Chopra' ), NUM_OF_MOV_BY_ACTOR_DIRECTOR AS ( SELECT TRIM(MC.PID) AS ACTOR_PID, TRIM(MD.PID) AS DIRECTOR_PID, COUNT(DISTINCT TRIM(MD.MID)) AS NUM_OF_MOV FROM M_Cast MC JOIN M_Director MD ON TRIM(MC.MID) = TRIM(MD.MID) GROUP BY ACTOR_PID, DIRECTOR_PID ), NUM_OF_MOVIES_BY_YC AS ( SELECT NM.ACTOR_PID, NM.DIRECTOR_PID, NM.NUM_OF_MOV AS NUM_OF_MOV_BY_YC FROM NUM_OF_MOV_BY_ACTOR_DIRECTOR NM JOIN YASH_CHOPRAS_PID YCP ON NM.DIRECTOR_PID = YCP.PID ), MAX_MOV_BY_OTHER_DIRECTORS AS ( SELECT ACTOR_PID, MAX(NUM_OF_MOV) AS MAX_NUM_OF_MOV FROM NUM_OF_MOV_BY_ACTOR_DIRECTOR NM JOIN YASH_CHOPRAS_PID YCP ON NM.DIRECTOR_PID <> YCP.PID GROUP BY ACTOR_PID ), ACTORS_MOV_COMPARISION AS ( SELECT NMY.ACTOR_PID, CASE WHEN NMY.NUM_OF_MOV_BY_YC > IFNULL(NMO.MAX_NUM_OF_MOV, 0) THEN 'Y' ELSE 'N' END AS MORE_MOV_BY_YC FROM NUM_OF_MOVIES_BY_YC NMY LEFT OUTER JOIN MAX_MOV_BY_OTHER_DIRECTORS NMO ON NMY.ACTOR_PID = NMO.ACTOR_PID ) SELECT COUNT(DISTINCT TRIM(P.PID)) AS ""Number of actor"" FROM Person P WHERE TRIM(P.PID) IN ( SELECT DISTINCT ACTOR_PID FROM ACTORS_MOV_COMPARISION WHERE MORE_MOV_BY_YC = 'Y' ); ",lite,local099,m_*.mid; m_*.pid; person.name; person.pid,4,42,True,ok,False,local099 sf_local131,ENTERTAINMENTAGENCY,duckdb,"Could you list each musical style with the number of times it appears as a 1st, 2nd, or 3rd preference in a single row per style?","SELECT Musical_Styles.StyleName, COUNT(RankedPreferences.FirstStyle) AS FirstPreference, COUNT(RankedPreferences.SecondStyle) AS SecondPreference, COUNT(RankedPreferences.ThirdStyle) AS ThirdPreference FROM Musical_Styles, (SELECT (CASE WHEN Musical_Preferences.PreferenceSeq = 1 THEN Musical_Preferences.StyleID ELSE Null END) As FirstStyle, (CASE WHEN Musical_Preferences.PreferenceSeq = 2 THEN Musical_Preferences.StyleID ELSE Null END) As SecondStyle, (CASE WHEN Musical_Preferences.PreferenceSeq = 3 THEN Musical_Preferences.StyleID ELSE Null END) AS ThirdStyle FROM Musical_Preferences) AS RankedPreferences WHERE Musical_Styles.StyleID = RankedPreferences.FirstStyle OR Musical_Styles.StyleID = RankedPreferences.SecondStyle OR Musical_Styles.StyleID = RankedPreferences.ThirdStyle GROUP BY StyleID, StyleName HAVING COUNT(FirstStyle) > 0 OR COUNT(SecondStyle) > 0 OR COUNT(ThirdStyle) > 0 ORDER BY FirstPreference DESC, SecondPreference DESC, ThirdPreference DESC, StyleID;",lite,local131,musical_preferences.preferenceseq; musical_preferences.styleid; musical_styles.styleid; musical_styles.stylename,4,76,True,ok,False,local131 sf_local163,EDUCATION_BUSINESS,duckdb,"Which university faculty members' salaries are closest to the average salary for their respective ranks? Please provide the ranks, first names, last names, and salaries.university","WITH AvgSalaries AS ( SELECT facrank AS FacRank, AVG(facsalary) AS AvSalary FROM university_faculty GROUP BY facrank ), SalaryDifferences AS ( SELECT university_faculty.facrank AS FacRank, university_faculty.facfirstname AS FacFirstName, university_faculty.faclastname AS FacLastName, university_faculty.facsalary AS Salary, ABS(university_faculty.facsalary - AvgSalaries.AvSalary) AS Diff FROM university_faculty JOIN AvgSalaries ON university_faculty.facrank = AvgSalaries.FacRank ), MinDifferences AS ( SELECT FacRank, MIN(Diff) AS MinDiff FROM SalaryDifferences GROUP BY FacRank ) SELECT s.FacRank, s.FacFirstName, s.FacLastName, s.Salary FROM SalaryDifferences s JOIN MinDifferences m ON s.FacRank = m.FacRank AND s.Diff = m.MinDiff; ",lite,local163,university_faculty.facfirstname; university_faculty.faclastname; university_faculty.facrank; university_faculty.facsalary,4,98,True,fix,False,local163 sf_local197,SQLITE_SAKILA,duckdb,"Among our top 10 paying customers, can you identify the largest change in payment amounts from one month to the immediately following month? Specifically, please determine for which customer and during which month this maximum month-over-month difference occurred, and provide the difference rounded to two decimal places.","WITH result_table AS ( SELECT strftime('%m', pm.payment_date) AS pay_mon, customer_id, COUNT(pm.amount) AS pay_countpermon, SUM(pm.amount) AS pay_amount FROM payment AS pm GROUP BY pay_mon, customer_id ), top10_customer AS ( SELECT customer_id, SUM(tb.pay_amount) AS total_payments FROM result_table AS tb GROUP BY customer_id ORDER BY SUM(tb.pay_amount) DESC LIMIT 10 ), difference_per_mon AS ( SELECT pay_mon AS month_number, pay_mon AS month, tb.pay_countpermon, tb.pay_amount, ABS(tb.pay_amount - LAG(tb.pay_amount) OVER (PARTITION BY tb.customer_id)) AS diff FROM result_table tb JOIN top10_customer top ON top.customer_id = tb.customer_id ) SELECT month, ROUND(max_diff, 2) AS max_diff FROM ( SELECT month, diff, month_number, MAX(diff) OVER (PARTITION BY month) AS max_diff FROM difference_per_mon ) AS max_per_mon WHERE diff = max_diff ORDER BY max_diff DESC LIMIT 1; ",lite,local197,payment.amount; payment.customer_id; payment.payment_date,3,89,True,ok,False,local197 sf_local199,SQLITE_SAKILA,snowflake,"Can you identify the year and month with the highest rental orders created by the store's staff for each store? Please list the store ID, the year, the month, and the total rentals for those dates.","WITH rentals_with_store AS ( SELECT s.""store_id"" AS ""store_id"", TRY_TO_TIMESTAMP(r.""rental_date"") AS ""rental_ts"" FROM ""SQLITE_SAKILA"".""SQLITE_SAKILA"".""RENTAL"" r JOIN ""SQLITE_SAKILA"".""SQLITE_SAKILA"".""STAFF"" s ON r.""staff_id"" = s.""staff_id"" WHERE TRY_TO_TIMESTAMP(r.""rental_date"") IS NOT NULL ), monthly_counts AS ( SELECT ""store_id"", EXTRACT(YEAR FROM ""rental_ts"") AS ""year"", EXTRACT(MONTH FROM ""rental_ts"") AS ""month"", COUNT(*) AS ""total_rentals"" FROM rentals_with_store GROUP BY ""store_id"", ""year"", ""month"" ) SELECT ""store_id"", ""year"", ""month"", ""total_rentals"" FROM monthly_counts QUALIFY DENSE_RANK() OVER ( PARTITION BY ""store_id"" ORDER BY ""total_rentals"" DESC ) = 1 ORDER BY ""store_id"", ""year"", ""month""",snow,sf_local199,rental.rental_date; rental.staff_id; staff.staff_id; staff.store_id,4,89,True,ok,False,local199 sf_local210,DELIVERY_CENTER,snowflake,Can you identify the hubs that saw more than a 20% increase in finished orders from February to March?,"WITH completed_orders AS ( SELECT o.""order_id"", o.""store_id"", o.""order_created_month"", o.""order_created_year"" FROM DELIVERY_CENTER.DELIVERY_CENTER.ORDERS o WHERE o.""order_created_year"" = 2021 AND o.""order_created_month"" IN (2,3) AND UPPER(TRIM(o.""order_status"")) = 'FINISHED' ) SELECT h.""hub_id"" AS ""hub_id"", h.""hub_name"" AS ""hub_name"", CAST(SUM(CASE WHEN c.""order_created_month"" = 2 THEN 1 ELSE 0 END) AS INTEGER) AS ""orders_february"", CAST(SUM(CASE WHEN c.""order_created_month"" = 3 THEN 1 ELSE 0 END) AS INTEGER) AS ""orders_march"", ( CAST(SUM(CASE WHEN c.""order_created_month"" = 3 THEN 1 ELSE 0 END) AS FLOAT) - CAST(SUM(CASE WHEN c.""order_created_month"" = 2 THEN 1 ELSE 0 END) AS FLOAT) ) / NULLIF(CAST(SUM(CASE WHEN c.""order_created_month"" = 2 THEN 1 ELSE 0 END) AS FLOAT), 0) AS ""pct_increase"" FROM completed_orders c JOIN DELIVERY_CENTER.DELIVERY_CENTER.STORES s ON c.""store_id"" = s.""store_id"" JOIN DELIVERY_CENTER.DELIVERY_CENTER.HUBS h ON s.""hub_id"" = h.""hub_id"" GROUP BY h.""hub_id"", h.""hub_name"" HAVING SUM(CASE WHEN c.""order_created_month"" = 2 THEN 1 ELSE 0 END) > 0 AND ( ( CAST(SUM(CASE WHEN c.""order_created_month"" = 3 THEN 1 ELSE 0 END) AS FLOAT) - CAST(SUM(CASE WHEN c.""order_created_month"" = 2 THEN 1 ELSE 0 END) AS FLOAT) ) / NULLIF(CAST(SUM(CASE WHEN c.""order_created_month"" = 2 THEN 1 ELSE 0 END) AS FLOAT), 0) ) > 0.2 ORDER BY ""pct_increase"" DESC, ""hub_id"" ASC;",snow,sf_local210,hubs.hub_id; hubs.hub_name; orders.order_created_month; orders.order_created_year; orders.order_id; orders.order_status; orders.store_id; stores.hub_id; stores.store_id,9,59,True,ok,False,local210 sf_local219,EU_SOCCER,duckdb,"In each league, considering all seasons, which single team has the fewest total match wins based on comparing home and away goals, including teams with zero wins, ensuring that if multiple teams tie for the fewest wins, only one team is returned for each league?","WITH match_view AS( SELECT M.id, L.name AS league, M.season, M.match_api_id, T.team_long_name AS home_team, TM.team_long_name AS away_team, M.home_team_goal, M.away_team_goal, P1.player_name AS home_gk, P2.player_name AS home_center_back_1, P3.player_name AS home_center_back_2, P4.player_name AS home_right_back, P5.player_name AS home_left_back, P6.player_name AS home_midfield_1, P7.player_name AS home_midfield_2, P8.player_name AS home_midfield_3, P9.player_name AS home_midfield_4, P10.player_name AS home_second_forward, P11.player_name AS home_center_forward, P12.player_name AS away_gk, P13.player_name AS away_center_back_1, P14.player_name AS away_center_back_2, P15.player_name AS away_right_back, P16.player_name AS away_left_back, P17.player_name AS away_midfield_1, P18.player_name AS away_midfield_2, P19.player_name AS away_midfield_3, P20.player_name AS away_midfield_4, P21.player_name AS away_second_forward, P22.player_name AS away_center_forward, M.goal, M.card FROM match M LEFT JOIN league L ON M.league_id = L.id LEFT JOIN team T ON M.home_team_api_id = T.team_api_id LEFT JOIN team TM ON M.away_team_api_id = TM.team_api_id LEFT JOIN player P1 ON M.home_player_1 = P1.player_api_id LEFT JOIN player P2 ON M.home_player_2 = P2.player_api_id LEFT JOIN player P3 ON M.home_player_3 = P3.player_api_id LEFT JOIN player P4 ON M.home_player_4 = P4.player_api_id LEFT JOIN player P5 ON M.home_player_5 = P5.player_api_id LEFT JOIN player P6 ON M.home_player_6 = P6.player_api_id LEFT JOIN player P7 ON M.home_player_7 = P7.player_api_id LEFT JOIN player P8 ON M.home_player_8 = P8.player_api_id LEFT JOIN player P9 ON M.home_player_9 = P9.player_api_id LEFT JOIN player P10 ON M.home_player_10 = P10.player_api_id LEFT JOIN player P11 ON M.home_player_11 = P11.player_api_id LEFT JOIN player P12 ON M.away_player_1 = P12.player_api_id LEFT JOIN player P13 ON M.away_player_2 = P13.player_api_id LEFT JOIN player P14 ON M.away_player_3 = P14.player_api_id LEFT JOIN player P15 ON M.away_player_4 = P15.player_api_id LEFT JOIN player P16 ON M.away_player_5 = P16.player_api_id LEFT JOIN player P17 ON M.away_player_6 = P17.player_api_id LEFT JOIN player P18 ON M.away_player_7 = P18.player_api_id LEFT JOIN player P19 ON M.away_player_8 = P19.player_api_id LEFT JOIN player P20 ON M.away_player_9 = P20.player_api_id LEFT JOIN player P21 ON M.away_player_10 = P21.player_api_id LEFT JOIN player P22 ON M.away_player_11 = P22.player_api_id ), match_score AS ( SELECT -- Displaying teams and their goals as home_team id, home_team AS team, CASE WHEN home_team_goal > away_team_goal THEN 1 ELSE 0 END AS Winning_match FROM match_view UNION ALL SELECT -- Displaying teams and their goals as away_team id, away_team AS team, CASE WHEN away_team_goal > home_team_goal THEN 1 ELSE 0 END AS Winning_match FROM match_view ), winning_matches AS ( SELECT -- Displaying total match wins for each team MV.league, M.team, COUNT(CASE WHEN M.Winning_match = 1 THEN 1 END) AS wins, ROW_NUMBER() OVER(PARTITION BY MV.league ORDER BY COUNT(CASE WHEN M.Winning_match = 1 THEN 1 END) ASC) AS rn FROM match_score M JOIN match_view MV ON M.id = MV.id GROUP BY MV.league, team ORDER BY league, wins ASC ) SELECT league, team FROM winning_matches WHERE rn = 1 -- Getting the team with the least number of wins in each league ORDER BY league;",lite,local219,league.id; league.name; match.away_player_1; match.away_player_10; match.away_player_11; match.away_player_2; match.away_player_3; match.away_player_4; match.away_player_5; match.away_player_6; match.away_player_7; match.away_player_8; match.away_player_9; match.away_team_api_id; match.away_team_goal; match.card; match.goal; match.home_player_1; match.home_player_10; match.home_player_11; match.home_player_2; match.home_player_3; match.home_player_4; match.home_player_5; match.home_player_6; match.home_player_7; match.home_player_8; match.home_player_9; match.home_team_api_id; match.home_team_goal; match.id; match.league_id; match.match_api_id; match.season; player.player_api_id; player.player_name; team.team_api_id; team.team_long_name,38,199,True,fix,True,local219 sf_local301,BANK_SALES_TRADING,duckdb,"For weekly-sales data, I need an analysis of our sales performance around mid-June for the years 2018, 2019, and 2020. Specifically, calculate the percentage change in sales between the four weeks leading up to June 15 and the four weeks following June 15 for each year.","SELECT before_effect, after_effect, after_effect - before_effect AS change_amount, ROUND(((after_effect * 1.0 / before_effect) - 1) * 100, 2) AS percent_change, '2018' AS year FROM ( SELECT SUM(CASE WHEN delta_weeks BETWEEN 1 AND 4 THEN sales END) AS after_effect, SUM(CASE WHEN delta_weeks BETWEEN -3 AND 0 THEN sales END) AS before_effect FROM ( SELECT week_date, ROUND((JULIANDAY(week_date) - JULIANDAY('2018-06-15')) / 7.0) + 1 AS delta_weeks, sales FROM cleaned_weekly_sales ) add_delta_weeks ) AS add_before_after UNION ALL SELECT before_effect, after_effect, after_effect - before_effect AS change_amount, ROUND(((after_effect * 1.0 / before_effect) - 1) * 100, 2) AS percent_change, '2019' AS year FROM ( SELECT SUM(CASE WHEN delta_weeks BETWEEN 1 AND 4 THEN sales END) AS after_effect, SUM(CASE WHEN delta_weeks BETWEEN -3 AND 0 THEN sales END) AS before_effect FROM ( SELECT week_date, ROUND((JULIANDAY(week_date) - JULIANDAY('2019-06-15')) / 7.0) + 1 AS delta_weeks, sales FROM cleaned_weekly_sales ) add_delta_weeks ) AS add_before_after UNION ALL SELECT before_effect, after_effect, after_effect - before_effect AS change_amount, ROUND(((after_effect * 1.0 / before_effect) - 1) * 100, 2) AS percent_change, '2020' AS year FROM ( SELECT SUM(CASE WHEN delta_weeks BETWEEN 1 AND 4 THEN sales END) AS after_effect, SUM(CASE WHEN delta_weeks BETWEEN -3 AND 0 THEN sales END) AS before_effect FROM ( SELECT week_date, ROUND((JULIANDAY(week_date) - JULIANDAY('2020-06-15')) / 7.0) + 1 AS delta_weeks, sales FROM cleaned_weekly_sales ) add_delta_weeks ) AS add_before_after ORDER BY year; ",lite,local301,cleaned_weekly_sales.sales; cleaned_weekly_sales.week_date,2,106,True,ok,False,local301 sf_local309,F1,snowflake,"For each year, which driver and which constructor scored the most points? I want the full name of each driver.","WITH ""years"" AS ( SELECT DISTINCT r.""year"" FROM ""F1"".""F1"".""RACES"" r ), ""final_races"" AS ( SELECT r.""year"", r.""race_id"" FROM ""F1"".""F1"".""RACES"" r JOIN ( SELECT ""year"", MAX(""round"") AS ""max_round"" FROM ""F1"".""F1"".""RACES"" GROUP BY ""year"" ) lr ON r.""year"" = lr.""year"" AND r.""round"" = lr.""max_round"" ), ""driver_top_standings"" AS ( SELECT fr.""year"", ds.""driver_id"", d.""full_name"" AS ""driver_full_name"", ds.""points"" AS ""driver_points"" FROM ""F1"".""F1"".""DRIVER_STANDINGS"" ds JOIN ""final_races"" fr ON ds.""race_id"" = fr.""race_id"" JOIN ( SELECT fr.""year"", MAX(ds.""points"") AS ""max_points"" FROM ""F1"".""F1"".""DRIVER_STANDINGS"" ds JOIN ""final_races"" fr ON ds.""race_id"" = fr.""race_id"" GROUP BY fr.""year"" ) md ON fr.""year"" = md.""year"" AND ds.""points"" = md.""max_points"" LEFT JOIN ""F1"".""F1"".""DRIVERS"" d ON ds.""driver_id"" = d.""driver_id"" ), ""driver_points_agg"" AS ( SELECT r.""year"" AS ""year"", res.""driver_id"" AS ""driver_id"", SUM(COALESCE(res.""points"", 0)) AS ""points"" FROM ""F1"".""F1"".""RESULTS"" res JOIN ""F1"".""F1"".""RACES"" r ON res.""race_id"" = r.""race_id"" GROUP BY r.""year"", res.""driver_id"" UNION ALL SELECT r.""year"" AS ""year"", sr.""driver_id"" AS ""driver_id"", SUM(COALESCE(sr.""points"", 0)) AS ""points"" FROM ""F1"".""F1"".""SPRINT_RESULTS"" sr JOIN ""F1"".""F1"".""RACES"" r ON sr.""race_id"" = r.""race_id"" GROUP BY r.""year"", sr.""driver_id"" ), ""driver_points_summed"" AS ( SELECT ""year"", ""driver_id"", SUM(""points"") AS ""points"" FROM ""driver_points_agg"" GROUP BY ""year"", ""driver_id"" ), ""driver_top_results"" AS ( SELECT dp.""year"", dp.""driver_id"", d.""full_name"" AS ""driver_full_name"", dp.""points"" AS ""driver_points"" FROM ""driver_points_summed"" dp JOIN ( SELECT ""year"", MAX(""points"") AS ""max_points"" FROM ""driver_points_summed"" GROUP BY ""year"" ) md ON dp.""year"" = md.""year"" AND dp.""points"" = md.""max_points"" LEFT JOIN ""F1"".""F1"".""DRIVERS"" d ON dp.""driver_id"" = d.""driver_id"" ), ""driver_top_final"" AS ( SELECT y.""year"", COALESCE(dts.""driver_id"", dtr.""driver_id"") AS ""driver_id"", COALESCE(dts.""driver_full_name"", dtr.""driver_full_name"") AS ""driver_full_name"" FROM ""years"" y LEFT JOIN ""driver_top_standings"" dts ON dts.""year"" = y.""year"" LEFT JOIN ""driver_top_results"" dtr ON dtr.""year"" = y.""year"" AND dts.""year"" IS NULL ), ""constructor_top_standings"" AS ( SELECT fr.""year"", cs.""constructor_id"", c.""name"" AS ""constructor_name"", cs.""points"" AS ""constructor_points"" FROM ""F1"".""F1"".""CONSTRUCTOR_STANDINGS"" cs JOIN ""final_races"" fr ON cs.""race_id"" = fr.""race_id"" JOIN ( SELECT fr.""year"", MAX(cs.""points"") AS ""max_points"" FROM ""F1"".""F1"".""CONSTRUCTOR_STANDINGS"" cs JOIN ""final_races"" fr ON cs.""race_id"" = fr.""race_id"" GROUP BY fr.""year"" ) mc ON fr.""year"" = mc.""year"" AND cs.""points"" = mc.""max_points"" LEFT JOIN ""F1"".""F1"".""CONSTRUCTORS"" c ON cs.""constructor_id"" = c.""constructor_id"" ), ""constructor_points_agg"" AS ( SELECT r.""year"" AS ""year"", res.""constructor_id"" AS ""constructor_id"", SUM(COALESCE(res.""points"", 0)) AS ""points"" FROM ""F1"".""F1"".""RESULTS"" res JOIN ""F1"".""F1"".""RACES"" r ON res.""race_id"" = r.""race_id"" GROUP BY r.""year"", res.""constructor_id"" UNION ALL SELECT r.""year"" AS ""year"", sr.""constructor_id"" AS ""constructor_id"", SUM(COALESCE(sr.""points"", 0)) AS ""points"" FROM ""F1"".""F1"".""SPRINT_RESULTS"" sr JOIN ""F1"".""F1"".""RACES"" r ON sr.""race_id"" = r.""race_id"" GROUP BY r.""year"", sr.""constructor_id"" ), ""constructor_points_summed"" AS ( SELECT ""year"", ""constructor_id"", SUM(""points"") AS ""points"" FROM ""constructor_points_agg"" GROUP BY ""year"", ""constructor_id"" ), ""constructor_top_results"" AS ( SELECT cp.""year"", cp.""constructor_id"", c.""name"" AS ""constructor_name"", cp.""points"" AS ""constructor_points"" FROM ""constructor_points_summed"" cp JOIN ( SELECT ""year"", MAX(""points"") AS ""max_points"" FROM ""constructor_points_summed"" GROUP BY ""year"" ) mc ON cp.""year"" = mc.""year"" AND cp.""points"" = mc.""max_points"" LEFT JOIN ""F1"".""F1"".""CONSTRUCTORS"" c ON cp.""constructor_id"" = c.""constructor_id"" ), ""constructor_top_final"" AS ( SELECT y.""year"", COALESCE(cts.""constructor_id"", ctr.""constructor_id"") AS ""constructor_id"", COALESCE(cts.""constructor_name"", ctr.""constructor_name"") AS ""constructor_name"" FROM ""years"" y LEFT JOIN ""constructor_top_standings"" cts ON cts.""year"" = y.""year"" LEFT JOIN ""constructor_top_results"" ctr ON ctr.""year"" = y.""year"" AND cts.""year"" IS NULL ) SELECT y.""year"", dtf.""driver_full_name"", ctf.""constructor_name"" FROM ""years"" y LEFT JOIN ""driver_top_final"" dtf ON dtf.""year"" = y.""year"" LEFT JOIN ""constructor_top_final"" ctf ON ctf.""year"" = y.""year"" ORDER BY y.""year"" ASC;",snow,sf_local309,constructor_standings.constructor_id; constructor_standings.points; constructor_standings.race_id; constructors.constructor_id; constructors.name; driver_standings_*.driver_id; driver_standings_*.points; driver_standings_*.race_id; drivers.driver_id; drivers_ext.full_name; races.race_id; races.round; races.year; results.constructor_id; results.driver_id; results.points; results.race_id; sprint_results.constructor_id; sprint_results.driver_id; sprint_results.points; sprint_results.race_id,21,221,True,ok,False,local309