【问题标题】:SQL Count distinct number of rows in table in GBQSQL计算GBQ中表中的不同行数
【发布时间】:2020-11-17 20:05:06
【问题描述】:

我想计算表中不同行的数量。我知道我可以使用 groupby 或一一命名所有列来做到这一点,但我只想这样做:

select count(distinct *) from my_table

这可能吗?

【问题讨论】:

  • 表有主键吗?

标签: sql count google-bigquery


【解决方案1】:

派生表(子查询)中执行SELECT DISTINCT,然后计算返回的行数。

select count(*) from
(select distinct * from my_table) dt

(你的表没有主键吗?)

【讨论】:

    【解决方案2】:

    你可以使用to_json_string():

    select count(distinct to_json_string(t))
    from t;
    

    【讨论】:

    • 谢谢戈登!我喜欢这种语法!
    【解决方案3】:

    以下是 BigQuery Standard SQL 的更多选项

    select count(distinct format('%t', t))
    from `project.dataset.table` t
    

    取决于您的用例 - 近似计数可能是更好的选择

    select approx_count_distinct(format('%t', t))
    from `project.dataset.table` t
    

    APPROX_COUNT_DISTINCT - 返回 COUNT(DISTINCT 表达式)的近似结果。返回的值是统计估计值,不一定是实际值。此函数不如 COUNT(DISTINCT 表达式) 准确,但在大量输入时表现更好

    【讨论】:

    • 谢谢米哈伊尔!并为更大的表添加 approx_count_distinct。
    【解决方案4】:

    不允许使用count(distinct *)

    或者,您可以明确命名列(定义唯一性)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-13
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-24
      • 2021-02-26
      • 2019-07-12
      • 1970-01-01
      相关资源
      最近更新 更多