def build_query_statement(min_priority_year, cpc_code_list, keep_pct):
  """Build a query to be run against the Google Patents Public Datasets.

  Args:
    min_priority_year: Integer noting the earliest year to include in results.
    cpc_code_list: A comma separated list of digits like 'A,B,C' which indicate
      the CPC groups to include in the results.
    keep_pct: A decimal between 0 and 1 indicating what percentage of records to
      return in the query. Useful for limiting the size of output during
      training with multiple CPC codes..

  Returns:
    Query: A string query in standardSQL syntax to run against BigQuery.
  """
  # Turn comma separated list of CPC code digits into SQL 'in' statement.
  cpc_codes = '(' + str(cpc_code_list.split(','))[1:-1] + ')'
  query = """
  #standardSQL
  with cpc4_quantiles as (
    SELECT
    cpc4, APPROX_QUANTILES(priority_yr, 4) as quantiles
    FROM (
      SELECT DISTINCT
      family_id,
      FLOOR(priority_date / 10000) as priority_yr,
      SUBSTR(cpc.code, 1, 4) cpc4 # Trim CPC Code to first 4 digits.
      FROM `patents-public-data.patents.publications`,
      UNNEST(cpc) as cpc
      WHERE country_code = 'US'
      AND FLOOR(priority_date / 10000) > {YEAR}
      AND substr(cpc.code, 1,1) in {CPCS}
    )
    GROUP BY 1
  )


  SELECT DISTINCT
    t1.publication_number,
    t1.fullclaim,
    t1.priority_yr,
    t1.cpc4,
    q.quantiles[offset(2)] as median_priority_yr
  FROM (
    SELECT
      p.publication_number,
      claims.text fullclaim,
      cast(priority_date/10000 as int64) priority_yr,
      substr(any_value(cpc.code),1,4) cpc4
    FROM `patents-public-data.patents.publications` p
    ,UNNEST(claims_localized) claims
    ,UNNEST(cpc) cpc
    WHERE claims.language = 'en'
    AND cpc.inventive = true
    AND cpc.first = true
    AND country_code = 'US'
    AND claims.text is not null
    AND substr(cpc.code, 1,1) in {CPCS}
    AND FLOOR(priority_date / 10000) > {YEAR}
    group by 1,2,3
  ) t1
  JOIN cpc4_quantiles q on t1.cpc4 = q.cpc4
  where rand() < {KEEP_PCT}
  """.format(CPCS=cpc_codes, YEAR=min_priority_year, KEEP_PCT=keep_pct)
  return query