【问题标题】:Create column to get unique counts for a column per unique id创建列以获取每个唯一 ID 列的唯一计数
【发布时间】:2020-11-16 18:21:39
【问题描述】:

我有一个包含以下列的 postgre sql 表:

 person_id|date     |cat      

 1489358  |12-29-19 |tier1
 1489358  |12-29-19 |tier2
 1489350  |01-09-20 |tier1
 1489350  |01-09-20 |tier1

我想创建一个额外的列,在其中创建一个列来计算每个人 ID 的唯一类别。所以表格看起来像:

 person_id|date     |cat      |ct_cat
 1489358  |12-29-19 |tier1.   |2
 1489358  |12-29-19 |tier2    |2
 1489350  |01-09-20 |tier1.   |1
 1489350  |01-09-20 |tier1.   |1

我尝试了以下代码:

select distinct *, count(distinct cat) as ct_cat
into table_2
from table_1
group by person_id, date,  cat;

【问题讨论】:

    标签: sql postgresql group-by count


    【解决方案1】:

    如果你能简单地这样做就好了:

    select t1.*, count(distinct cat) over (partition by person_id)
    from table_1 t1;
    

    但是,Postgres 不支持 count(distinct) 作为窗口函数。使用dense_rank() 有一个简单的解决方法:

    select t1.*,
           (dense_rank() over (partition by person_id order by cat asc) +
            dense_rank() over (partition by person_id order by cat desc) 
           ) as num_cat
    from table_1 t1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多