选择计数表新字段中的不同列

时间:2018-06-29 18:45:17

标签: sql postgresql postgresql-9.5

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

test table image

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

1 个答案:

答案 0 :(得分:0)

您似乎想要:

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

A,Postgres在窗口函数中不支持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