select 计算 table 个新字段中的不同列

select count distinct column in table new filed

我有一个查询结果,有3个不同的p_id (3160, 3301, 41)

我想select count(distinct p_id) 如图所示p_id_count_true(见图),p_id_count不正确, 我如何编写子查询并获得 p_id_count_true

您似乎想要:

select . . .,
       count(distinct pid) over () as num_pids
from t

唉,Postgres 在 window 函数中不支持 distinct。一种解决方法是:

select . . .,
       sum( (seqnum_pid = 1)::int ) over () as num_pids
from (select t.*, row_number() over (partition by pid order by pid) as seqnum_pid
      from t
     ) t

有些人更喜欢 dense_rank() 方法:

select . . .,
       max( seqnum_pid ) over () as num_pids
from (select t.*, dense_rank() over (order by pid) as seqnum_pid
      from t
     ) t