nl2sqlproj/spider2-nl2sql huggingface dataset:
Database: ga4 (snowflake)
Question: 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) ?
SQL:
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;
Database: ga360 (snowflake)
Question: Find the top-selling product among customers who bought 'Youtube Men’s Vintage Henley' in July 2017, excluding itself.
SQL:
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;
Database: ga360 (snowflake)
Question: 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?
SQL:
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;
Database: ga360 (snowflake)
Question: 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?
SQL:
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;
Database: ga360 (snowflake)
Question: 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?
SQL:
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;
Database: ga360 (snowflake)
Question: 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
SQL:
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;
Database: ga360 (snowflake)
Question: 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?
SQL:
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;
Database: ga360 (snowflake)
Question: 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?
SQL:
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;
Database: ga360 (snowflake)
Question: 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.
SQL:
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
Database: ga360 (snowflake)
Question: 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.
SQL:
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
Database: ga360 (snowflake)
Question: 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?
SQL:
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;
Database: ga360 (snowflake)
Question: 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?
SQL:
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";
Database: ga360 (snowflake)
Question: 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.
SQL:
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;
Database: PATENTS (snowflake)
Question: In which year did the assignee with the most applications in the patent category 'A61' file the most?
SQL:
WITH AA AS (
    SELECT 
        FIRST_VALUE("assignee_harmonized") OVER (PARTITION BY "application_number" ORDER BY "application_number") AS assignee_harmonized,
        FIRST_VALUE("filing_date") OVER (PARTITION BY "application_number" ORDER BY "application_number") AS filing_date,
        "application_number"
    FROM 
        PATENTS.PATENTS.PUBLICATIONS AS pubs
        , LATERAL FLATTEN(input => pubs."cpc") AS c
    WHERE 
        c.value:"code" LIKE 'A61%'
),

PatentApplications AS (
    SELECT 
        ANY_VALUE(assignee_harmonized) as assignee_harmonized,
        ANY_VALUE(filing_date) as filing_date
    FROM AA
    GROUP BY "application_number"
),

AssigneeApplications AS (
SELECT 
    COUNT(*) AS total_applications,
    a.value::STRING AS assignee_name,
    CAST(FLOOR(filing_date / 10000) AS INT) AS filing_year
FROM 
    PatentApplications
    , LATERAL FLATTEN(input => assignee_harmonized) AS a
GROUP BY 
    a.value::STRING, filing_year
),

TotalApplicationsPerAssignee AS (
    SELECT
        assignee_name,
        SUM(total_applications) AS total_applications
    FROM 
        AssigneeApplications
    GROUP BY 
        assignee_name
    ORDER BY 
        total_applications DESC
    LIMIT 1
),

MaxYearForTopAssignee AS (
    SELECT
        aa.assignee_name,
        aa.filing_year,
        aa.total_applications
    FROM 
        AssigneeApplications aa
    INNER JOIN
        TotalApplicationsPerAssignee tapa ON aa.assignee_name = tapa.assignee_name
    ORDER BY 
        aa.total_applications DESC
    LIMIT 1
)

SELECT filing_year
FROM 
    MaxYearForTopAssignee
Database: PATENTS (snowflake)
Question: 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.
SQL:
WITH PatentApplications AS (
   SELECT 
        "assignee_harmonized" AS assignee_harmonized,
        "filing_date" AS filing_date,
        "country_code" AS country_code,
        "application_number" AS application_number
    FROM 
        PATENTS.PATENTS.PUBLICATIONS AS pubs,
        LATERAL FLATTEN(input => pubs."cpc") AS c
    WHERE c.value:"code" LIKE 'A01B3%'

),

AssigneeApplications AS (
    SELECT 
        COUNT(*) AS year_country_cnt,
        a.value:"name" AS assignee_name,
        CAST(FLOOR(filing_date / 10000) AS INT) AS filing_year,
        apps.country_code as country_code
    FROM 
        PatentApplications as apps,
        LATERAL FLATTEN(input => assignee_harmonized) AS a
    GROUP BY 
        assignee_name, filing_year, country_code
),

RankedApplications AS (
    SELECT
        assignee_name,
        filing_year,
        country_code,
        year_country_cnt,
        SUM(year_country_cnt) OVER (PARTITION BY assignee_name, filing_year) AS total_cnt,
        ROW_NUMBER() OVER (PARTITION BY assignee_name, filing_year ORDER BY year_country_cnt DESC) AS rn
    FROM
        AssigneeApplications
),

AggregatedData AS (
    SELECT
        total_cnt AS year_cnt,
        assignee_name,
        filing_year,
        country_code
    FROM
        RankedApplications
    WHERE
        rn = 1
)


SELECT 
    total_count,
    REPLACE(assignee_name, '"', '') AS assignee_name,
    year_cnt,
    filing_year,
    country_code
FROM (
    SELECT 
        year_cnt,
        assignee_name,
        filing_year,
        country_code,
        SUM(year_cnt) OVER (PARTITION BY assignee_name) AS total_count,
        ROW_NUMBER() OVER (PARTITION BY assignee_name ORDER BY year_cnt DESC) AS rn
    FROM
        AggregatedData
    ORDER BY assignee_name
) sub
WHERE rn = 1
ORDER BY total_count
DESC
LIMIT 3
Database: PATENTS (snowflake)
Question: 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?
SQL:
WITH Patent_Matches AS (
    SELECT
      TO_DATE(CAST(ANY_VALUE(patentsdb."filing_date") AS STRING), 'YYYYMMDD') AS Patent_Filing_Date,
      patentsdb."application_number" AS Patent_Application_Number,
      MAX(abstract_info.value:"text") AS Patent_Title,
      MAX(abstract_info.value:"language") AS Patent_Title_Language
    FROM
      PATENTS.PATENTS.PUBLICATIONS AS patentsdb,
      LATERAL FLATTEN(input => patentsdb."abstract_localized") AS abstract_info
    WHERE
      LOWER(abstract_info.value:"text") LIKE '%internet of things%'
      AND patentsdb."country_code" = 'US'
    GROUP BY
      Patent_Application_Number
),

Date_Series_Table AS (
    SELECT
        DATEADD(day, seq4(), DATE '2008-01-01') AS day,
        0 AS Number_of_Patents
    FROM
        TABLE(
            GENERATOR(
                ROWCOUNT => 5479
            )
        )
    ORDER BY
        day
)

SELECT
  TO_CHAR(Date_Series_Table.day, 'YYYY-MM') AS Patent_Date_YearMonth,
  COUNT(Patent_Matches.Patent_Application_Number) AS Number_of_Patent_Applications
FROM
  Date_Series_Table
  LEFT JOIN Patent_Matches
    ON Date_Series_Table.day = Patent_Matches.Patent_Filing_Date
WHERE
    Date_Series_Table.day < DATE '2023-01-01'
GROUP BY
  TO_CHAR(Date_Series_Table.day, 'YYYY-MM')
ORDER BY
  Patent_Date_YearMonth;
Database: PATENTS (snowflake)
Question: 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.
SQL:
WITH patents_sample AS (
    SELECT
        t1."publication_number",
        t1."application_number"
    FROM
        PATENTS.PATENTS.PUBLICATIONS t1
    WHERE
        TO_DATE(
            CASE
                WHEN t1."grant_date" != 0 THEN TO_CHAR(t1."grant_date")
                ELSE NULL
            END, 
            'YYYYMMDD'
        ) BETWEEN TO_DATE('20100101', 'YYYYMMDD') AND TO_DATE('20101231', 'YYYYMMDD')
),
forward_citation AS (
    SELECT
        patents_sample."publication_number",
        COUNT(DISTINCT t3."citing_application_number") AS "forward_citations"
    FROM
        patents_sample
        LEFT JOIN (
            SELECT
                x2."publication_number",
                TO_DATE(
                    CASE
                        WHEN x2."filing_date" != 0 THEN TO_CHAR(x2."filing_date")
                        ELSE NULL
                    END,
                    'YYYYMMDD'
                ) AS "filing_date"
            FROM
                PATENTS.PATENTS.PUBLICATIONS x2
            WHERE
                x2."filing_date" != 0
        ) t2
            ON t2."publication_number" = patents_sample."publication_number"
        LEFT JOIN (
            SELECT
                x3."publication_number" AS "citing_publication_number",
                x3."application_number" AS "citing_application_number",
                TO_DATE(
                    CASE
                        WHEN x3."filing_date" != 0 THEN TO_CHAR(x3."filing_date")
                        ELSE NULL
                    END,
                    'YYYYMMDD'
                ) AS "joined_filing_date",
                cite.value:"publication_number"::STRING AS "cited_publication_number"
            FROM
                PATENTS.PATENTS.PUBLICATIONS x3,
                LATERAL FLATTEN(INPUT => x3."citation") cite
            WHERE
                x3."filing_date" != 0
        ) t3
            ON patents_sample."publication_number" = t3."cited_publication_number"
            AND t3."joined_filing_date" BETWEEN t2."filing_date" AND DATEADD(YEAR, 10, t2."filing_date")
    GROUP BY
        patents_sample."publication_number"
)

SELECT
    COUNT(*)
FROM
    forward_citation
WHERE
    "forward_citations" = 1;
Database: PATENTS (snowflake)
Question: How many US B2 patents granted between 2008 and 2018 contain claims that do not include the word 'claim'?
SQL:
WITH patents_sample AS (
  SELECT 
    t1."publication_number" AS publication_number,
    claim.value:"text" AS claims_text
  FROM 
    PATENTS.PATENTS.PUBLICATIONS t1,
    LATERAL FLATTEN(input => t1."claims_localized") AS claim
  WHERE 
    t1."country_code" = 'US'
    AND t1."grant_date" BETWEEN 20080101 AND 20181231
    AND t1."grant_date" != 0
    AND t1."publication_number" LIKE '%B2%'
),
Publication_data AS (
  SELECT
    publication_number,
    COUNT_IF(claims_text NOT LIKE '%claim%') AS nb_indep_claims
  FROM
    patents_sample
  GROUP BY
    publication_number
)

SELECT COUNT(nb_indep_claims)
FROM Publication_data
WHERE nb_indep_claims != 0
Database: PATENTS (snowflake)
Question: What is the most common 4-digit IPC code among US B2 utility patents granted from June to August in 2022?
SQL:
WITH interim_table as(
SELECT 
    t1."publication_number", 
    SUBSTR(ipc_u.value:"code", 0, 4) as ipc4
FROM 
    PATENTS.PATENTS.PUBLICATIONS t1,
    LATERAL FLATTEN(input => t1."ipc") AS ipc_u
WHERE
"country_code" = 'US'  
AND "grant_date" between 20220601 AND 20220831
  AND "grant_date" != 0
  AND "publication_number" LIKE '%B2%'  
GROUP BY 
    t1."publication_number", 
    ipc4
) 
SELECT 
ipc4
FROM 
interim_table 
GROUP BY ipc4
ORDER BY COUNT("publication_number") DESC
LIMIT 1
Database: PATENTS_GOOGLE (snowflake)
Question: 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.
SQL:
WITH patents_sample AS (
    SELECT 
        "publication_number", 
        "application_number"
    FROM
        PATENTS_GOOGLE.PATENTS_GOOGLE.PUBLICATIONS
    WHERE
        "publication_number" = 'US-9741766-B2'
),
flattened_t5 AS (
    SELECT
        t5."publication_number",
        f.value AS element_value,
        f.index AS pos
    FROM
        PATENTS_GOOGLE.PATENTS_GOOGLE.ABS_AND_EMB t5,
        LATERAL FLATTEN(input => t5."embedding_v1") AS f
),
flattened_t6 AS (
    SELECT
        t6."publication_number",
        f.value AS element_value,
        f.index AS pos
    FROM
        PATENTS_GOOGLE.PATENTS_GOOGLE.ABS_AND_EMB t6,
        LATERAL FLATTEN(input => t6."embedding_v1") AS f
),
similarities AS (
    SELECT
        t1."publication_number" AS base_publication_number,
        t4."publication_number" AS similar_publication_number,
        SUM(ft5.element_value * ft6.element_value) AS similarity
    FROM
        (SELECT * FROM patents_sample LIMIT 1) t1
    LEFT JOIN (
        SELECT 
            x3."publication_number",
            EXTRACT(YEAR, TO_DATE(CAST(x3."filing_date" AS STRING), 'YYYYMMDD')) AS focal_filing_year
        FROM 
            PATENTS_GOOGLE.PATENTS_GOOGLE.PUBLICATIONS x3
        WHERE 
            x3."filing_date" != 0
    ) t3 ON t3."publication_number" = t1."publication_number"
    LEFT JOIN (
        SELECT 
            x4."publication_number",
            EXTRACT(YEAR, TO_DATE(CAST(x4."filing_date" AS STRING), 'YYYYMMDD')) AS filing_year
        FROM 
            PATENTS_GOOGLE.PATENTS_GOOGLE.PUBLICATIONS x4
        WHERE 
            x4."filing_date" != 0
    ) t4 ON
        t4."publication_number" != t1."publication_number"
        AND t3.focal_filing_year = t4.filing_year
    LEFT JOIN flattened_t5 AS ft5 ON ft5."publication_number" = t1."publication_number"
    LEFT JOIN flattened_t6 AS ft6 ON ft6."publication_number" = t4."publication_number"
    AND ft5.pos = ft6.pos  -- Align vector positions
    GROUP BY
        t1."publication_number", t4."publication_number"
)
SELECT
    s.similar_publication_number,
    s.similarity
FROM (
    SELECT
        s.*,
        ROW_NUMBER() OVER (PARTITION BY s.base_publication_number ORDER BY s.similarity DESC) AS seqnum
    FROM
        similarities s
) s
WHERE
    seqnum <= 5;
Database: PATENTS (snowflake)
Question: 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.
SQL:
WITH patent_cpcs AS (
    SELECT
        cd."parents",
        CAST(FLOOR("filing_date" / 10000) AS INT) AS "filing_year"
    FROM (
        SELECT MAX("cpc") AS "cpc", MAX("filing_date") AS "filing_date"
        FROM "PATENTS"."PATENTS"."PUBLICATIONS"
        WHERE "application_number" != ''
          AND "country_code" = 'DE'
          AND "grant_date" >= 20161201
          AND "grant_date" <= 20161231
        GROUP BY "application_number"
    ), LATERAL FLATTEN(INPUT => "cpc") AS cpcs
    JOIN "PATENTS"."PATENTS"."CPC_DEFINITION" cd ON cd."symbol" = cpcs.value:"code"
    WHERE cpcs.value:"first" = TRUE
      AND "filing_date" > 0
),
yearly_counts AS (
    SELECT
        "cpc_group",
        "filing_year",
        COUNT(*) AS "cnt"
    FROM (
        SELECT
            cpc_parent.VALUE AS "cpc_group",  -- Corrected reference to flattened "parents"
            "filing_year"
        FROM patent_cpcs,
             LATERAL FLATTEN(INPUT => "parents") AS cpc_parent  -- Corrected reference to flattened "parents"
    )
    GROUP BY "cpc_group", "filing_year"
),
moving_avg AS (
    SELECT
        "cpc_group",
        "filing_year",
        "cnt",
        AVG("cnt") OVER (PARTITION BY "cpc_group" ORDER BY "filing_year" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS "moving_avg"
    FROM yearly_counts
)
SELECT 
    c."titleFull",  -- Ensure correct column name (check case)
    REPLACE("cpc_group", '"', '') AS "cpc_group",
    MAX("filing_year") AS "best_filing_year"
FROM moving_avg
JOIN "PATENTS"."PATENTS"."CPC_DEFINITION" c ON "cpc_group" = c."symbol"
WHERE c."level" = 4
GROUP BY c."titleFull", "cpc_group"
ORDER BY c."titleFull", "cpc_group" ASC;
Database: PATENTS (snowflake)
Question: 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.
SQL:
WITH patent_cpcs AS (
    SELECT
        cd."parents",
        CAST(FLOOR("filing_date" / 10000) AS INT) AS "filing_year"
    FROM (
        SELECT
            MAX("cpc") AS "cpc", MAX("filing_date") AS "filing_date"
        FROM
            PATENTS.PATENTS.PUBLICATIONS
        WHERE 
            "application_number" != ''
        GROUP BY
            "application_number"
    ) AS publications
    , LATERAL FLATTEN(INPUT => "cpc") AS cpcs
    JOIN
        PATENTS.PATENTS.CPC_DEFINITION cd ON cd."symbol" = cpcs.value:"code"
    WHERE 
        cpcs.value:"first" = TRUE
          AND "filing_date" > 0

),
yearly_counts AS (
    SELECT
        "cpc_group",
        "filing_year",
        COUNT(*) AS "cnt"
    FROM (
        SELECT
            cpc_parent.value::STRING AS "cpc_group",
            "filing_year"
        FROM patent_cpcs,
             LATERAL FLATTEN(input => patent_cpcs."parents") AS cpc_parent
    )
    GROUP BY "cpc_group", "filing_year"
),
ordered_counts AS (
    SELECT
        "cpc_group",
        "filing_year",
        "cnt",
        ROW_NUMBER() OVER (PARTITION BY "cpc_group" ORDER BY "filing_year" ASC) AS rn
    FROM yearly_counts
),
recursive_ema AS (
    -- Anchor member: first year per cpc_group
    SELECT
        "cpc_group",
        "filing_year",
        "cnt",
        "cnt" * 0.2 + 0 * 0.8 AS "ema",
        rn
    FROM ordered_counts
    WHERE rn = 1

    UNION ALL

    -- Recursive member: subsequent years
    SELECT
        oc."cpc_group",
        oc."filing_year",
        oc."cnt",
        oc."cnt" * 0.2 + re."ema" * 0.8 AS "ema",
        oc.rn
    FROM ordered_counts oc
    JOIN recursive_ema re
        ON oc."cpc_group" = re."cpc_group"
       AND oc.rn = re.rn + 1
),
max_ema AS (
    SELECT
        "cpc_group",
        "filing_year",
        "ema"
    FROM recursive_ema
),
ranked_ema AS (
    SELECT
        me."cpc_group",
        me."filing_year",
        me."ema",
        ROW_NUMBER() OVER (
            PARTITION BY me."cpc_group" 
            ORDER BY me."ema" DESC, me."filing_year" DESC
        ) AS rn_rank
    FROM max_ema me
)
SELECT 
    c."titleFull",
    REPLACE(r."cpc_group", '"', '') AS "cpc_group",
    r."filing_year" AS "best_filing_year"
FROM ranked_ema r
JOIN "PATENTS"."PATENTS"."CPC_DEFINITION" c 
    ON r."cpc_group" = c."symbol"
WHERE 
    c."level" = 5
    AND r.rn_rank = 1
ORDER BY 
    c."titleFull", 
    "cpc_group" ASC;
Database: PATENTS (snowflake)
Question: 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.
SQL:
SELECT
    REPLACE(citing_assignee, '"', '') AS citing_assignee,
    cpcdef."titleFull" AS cpc_title,
    COUNT(*) AS number
FROM (
    SELECT
        pubs."publication_number" AS citing_publication_number,
        cite.value:"publication_number" AS cited_publication_number,
        citing_assignee_s.value:"name" AS citing_assignee,
        SUBSTR(cpcs.value:"code", 1, 4) AS citing_cpc_subclass
    FROM 
        PATENTS.PATENTS.PUBLICATIONS AS pubs
    , LATERAL FLATTEN(input => pubs."citation") AS cite
    , LATERAL FLATTEN(input => pubs."assignee_harmonized") AS citing_assignee_s
    , LATERAL FLATTEN(input => pubs."cpc") AS cpcs
    WHERE
        cpcs.value:"first" = TRUE
) AS pubs
JOIN (
    SELECT
        "publication_number" AS cited_publication_number,
        cited_assignee_s.value:"name" AS cited_assignee
    FROM
        PATENTS.PATENTS.PUBLICATIONS
    , LATERAL FLATTEN(input => "assignee_harmonized") AS cited_assignee_s
) AS refs
    ON pubs.cited_publication_number = refs.cited_publication_number
JOIN
    PATENTS.PATENTS.CPC_DEFINITION AS cpcdef
    ON cpcdef."symbol" = pubs.citing_cpc_subclass
WHERE
    refs.cited_assignee = 'DENSO CORP'
    AND pubs.citing_assignee != 'DENSO CORP'
GROUP BY
    citing_assignee, cpcdef."titleFull"
Database: PATENTS_USPTO (snowflake)
Question: Can you identify the top 5 patents that were initially rejected under section 101 with no allowed claims, based on the length of their granted claims? The patents should have been granted in the US between 2010 and 2023. Additionally, ensure to select the first office action date for each application. Please include their first publication numbers, along with their first publication dates, length of the filed claims and grant dates.
SQL:
Database: PATENTS_USPTO (snowflake)
Question: Could you provide the earliest publication numbers, corresponding application numbers, claim numbers, and word counts for the top 100 independent patent claims, based on the highest word count, retrieved from claims stats within uspto_oce_claims (filtered by ind_flg='1'), matched with their publication numbers from uspto_oce_claims match, and further joined with patents publications to ensure only the earliest publication for each application is included, ordered by descending word count, and limited to the top 100 results?
SQL:
Database: PATENTSVIEW (snowflake)
Question: 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.
SQL:
SELECT filterData."fwrdCitations_3"
FROM
  PATENTSVIEW.PATENTSVIEW.APPLICATION AS app
JOIN (
  SELECT DISTINCT 
    cpc."patent_id", 
    IFNULL(citation_3."bkwdCitations_3", 0) AS "bkwdCitations_3", 
    IFNULL(citation_3."fwrdCitations_3", 0) AS "fwrdCitations_3"
  FROM
    PATENTSVIEW.PATENTSVIEW.CPC_CURRENT AS cpc
  LEFT JOIN (
    SELECT 
      b."patent_id", 
      b."bkwdCitations_3", 
      f."fwrdCitations_3"
    FROM 
      (SELECT 
         cited."patent_id",
         COUNT(*) AS "fwrdCitations_3"
       FROM 
         PATENTSVIEW.PATENTSVIEW.USPATENTCITATION AS cited
       JOIN
         PATENTSVIEW.PATENTSVIEW.APPLICATION AS apps
         ON cited."patent_id" = apps."patent_id"
       WHERE
         apps."country" = 'US'
         AND cited."date" >= apps."date"
         AND TRY_CAST(cited."date" AS DATE) <= DATEADD(YEAR, 1, TRY_CAST(apps."date" AS DATE)) -- Citation within 1 year
       GROUP BY 
         cited."patent_id"
      ) AS f
    JOIN (
      SELECT 
        cited."patent_id",
        COUNT(*) AS "bkwdCitations_3"
      FROM 
        PATENTSVIEW.PATENTSVIEW.USPATENTCITATION AS cited
      JOIN
        PATENTSVIEW.PATENTSVIEW.APPLICATION AS apps
        ON cited."patent_id" = apps."patent_id"
      WHERE
        apps."country" = 'US'
        AND cited."date" < apps."date"
        AND TRY_CAST(cited."date" AS DATE) >= DATEADD(YEAR, -1, TRY_CAST(apps."date" AS DATE)) -- Citation within 1 year before
      GROUP BY 
        cited."patent_id"
    ) AS b
    ON b."patent_id" = f."patent_id"
    WHERE 
      b."bkwdCitations_3" IS NOT NULL
      AND f."fwrdCitations_3" IS NOT NULL
  ) AS citation_3 
  ON cpc."patent_id" = citation_3."patent_id"
) AS filterData
ON app."patent_id" = filterData."patent_id"
ORDER BY filterData."bkwdCitations_3" DESC
LIMIT 1;
Database: GITHUB_REPOS (snowflake)
Question: How can we identify the top 10 most frequently used packages in GitHub repository contents by looking for import statements enclosed in parentheses, splitting any multi-line imports by newlines, extracting package names that appear within double quotes, counting how often these packages appear, ignoring any null results, and finally ordering them in descending order of their frequency? The final answer should remove the quotation marks.
SQL:
Database: GITHUB_REPOS (snowflake)
Question: From GitHub Repos contents, how can we identify the top 10 most frequently imported package names in Java source files by splitting each file's content into lines, filtering for valid import statements, extracting only the package portion using a suitable regex, grouping by these extracted package names, counting their occurrences, and finally returning the 10 packages that appear most often in descending order of frequency?
SQL:
Database: GITHUB_REPOS_DATE (snowflake)
Question: Which primary programming languages, determined by the highest number of bytes in each repository, had at least 100 PullRequestEvents on January 18, 2023 across all their repositories?
SQL:
WITH
  event_data AS (
    SELECT
      "type",
      EXTRACT(YEAR FROM TO_TIMESTAMP("created_at" / 1000000)) AS "year",
      EXTRACT(QUARTER FROM TO_TIMESTAMP("created_at" / 1000000)) AS "quarter",
      REGEXP_REPLACE(
        "repo"::variant:"url"::string,
        'https:\\/\\/github\\.com\\/|https:\\/\\/api\\.github\\.com\\/repos\\/',
        ''
      ) AS "name"
    FROM GITHUB_REPOS_DATE.DAY._20230118
  ),

  repo_languages AS (
    SELECT
      "repo_name" AS "name",
      "lang"
    FROM (
      SELECT
        "repo_name",
        FIRST_VALUE("language") OVER (
          PARTITION BY "repo_name" ORDER BY "bytes" DESC
        ) AS "lang"
      FROM (
        SELECT
          "repo_name",
          "language".value:"name" AS "language",
          "language".value:"bytes" AS "bytes"
        FROM GITHUB_REPOS_DATE.GITHUB_REPOS.LANGUAGES,
        LATERAL FLATTEN(INPUT => "language") AS "language"
      )
    )
    WHERE "lang" IS NOT NULL
    GROUP BY "repo_name", "lang"
  ),

  joined_data AS (
    SELECT
      a."type" AS "type",
      b."lang" AS "language",
      a."year" AS "year",
      a."quarter" AS "quarter"
    FROM event_data a
    JOIN repo_languages b
      ON a."name" = b."name"
  ),

  count_data AS (
    SELECT
      "language",
      "year",
      "quarter",
      "type",
      COUNT(*) AS "count"
    FROM joined_data
    GROUP BY "type", "language", "year", "quarter"
    ORDER BY "year", "quarter", "count" DESC
  )

SELECT
  REPLACE("language", '"', '') AS "language_name",
  "count"
FROM count_data
WHERE "count" >= 5
  AND "type" = 'PullRequestEvent';