【问题标题】:Get the top patent countries, codes in a BQ public dataset在 BQ 公共数据集中获取顶级专利国家、代码
【发布时间】:2019-05-23 22:52:54
【问题描述】:

我正在尝试使用分析函数来获取专利申请量排名前 2 的国家/地区,并在这 2 个国家/地区中获取排名前 2 位的申请类型。例如,答案将如下所示:

country  -   code 
US           P
US           A
GB           X
GB           P

这是我用来获取此信息的查询:

SELECT
  country_code,
  MIN(count_country_code) count_country_code,
  application_kind
FROM (
  WITH
    A AS (
    SELECT
      country_code,
      COUNT(country_code) OVER (PARTITION BY country_code) AS count_country_code,
      application_kind
    FROM
      `patents-public-data.patents.publications`),
    B AS (
    SELECT
      country_code,
      count_country_code,
      DENSE_RANK() OVER(ORDER BY count_country_code DESC) AS country_code_num,
      application_kind,
      DENSE_RANK() OVER(PARTITION BY country_code ORDER BY count_country_code DESC) AS application_kind_num
    FROM
      A)
  SELECT
    country_code,
    count_country_code,
    application_kind
  FROM
    B
  WHERE
    country_code_num <= 2
    AND application_kind_num <= 2) x
GROUP BY
  country_code,
  application_kind
ORDER BY
  count_country_code DESC

但是,不幸的是,由于过度/订单/分区,我收到“超出内存”错误。这是消息:

查询执行期间资源超出:无法在分配的内存中执行查询。峰值使用量:限制的 112%。最高内存消耗者:用于分析 OVER() 子句的排序操作:98% 其他/未归因:2%

如何在不遇到这些内存错误的情况下进行上述查询(或其他类似查询)?这可以在公共数据集here 上进行测试。

一种粗略的方法(仅在字段具有半低基数的情况下才有效)是将其作为简单的聚合操作进行,并对数据库外部的内存中的结果进行排序。例如:

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    以下是 BigQuery 标准 SQL

    #standardSQL
    WITH A AS (
      SELECT country_code
      FROM `patents-public-data.patents.publications`
      GROUP BY country_code
      ORDER BY COUNT(1) DESC
      LIMIT 2
    ), B AS (
      SELECT
        country_code,
        application_kind,
        COUNT(1) application_kind_count
      FROM `patents-public-data.patents.publications`
      WHERE country_code IN (SELECT country_code FROM A)
      GROUP BY country_code, application_kind
    ), C AS (
      SELECT
        country_code,
        application_kind,
        application_kind_count,
        DENSE_RANK() OVER(PARTITION BY country_code ORDER BY application_kind_count DESC) AS application_kind_rank
      FROM B
    )
    SELECT
      country_code,
      application_kind,
      application_kind_count
    FROM C
    WHERE application_kind_rank <= 2  
    

    结果

    【讨论】:

    • 我明白了,感谢您的回复。所以这里的方法基本上是通过预过滤到那些最高值然后进行子选择来切断第一级。
    • 我认为,这是有道理的,否则你就是在“浪费”资源来计算所有已知会从最终结果中消除的排名
    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多