【问题标题】:Count distinct values depending on group根据组计算不同的值
【发布时间】:2021-04-05 12:10:19
【问题描述】:

我有一个名为“test”的表,其中两列如下所示:

identifier     group
12             a
35             c
87             b
35             c
22             c
....

这会持续数千行。我想知道的是每个“组”有多少不同的标识符。因此,例如使用上表,组“c”将有 2 个标识符,同一标识符可以在每个组中出现多次; 35 在 c 组中出现了两次,但我希望它只计算一次。

理想情况下,输出将是两列,如下所示:

group   distinct_id_count
a       1
b       1
c       2
... (these number would be much larger and there would be hundreds of more grouping in the actual table)

我正在考虑按行号进行过度分区,但我不太清楚它是如何工作的。

【问题讨论】:

    标签: sql count amazon-redshift


    【解决方案1】:

    你会使用count(distinct):

    select "group", count(distinct id)
    from t
    group by "group";
    

    请注意,group 是一个非常糟糕的列名称,因为它是一个 SQL 关键字。希望真正的列名更合理。

    【讨论】:

      猜你喜欢
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多