总和,其中至少N个记录等于x

时间:2017-12-13 01:02:37

标签: sql postgresql

如果ID字段中的N个值等于X量,那么有没有办法“查找”?

1 个答案:

答案 0 :(得分:1)

以下是3种可能的方式:

select *
from (
      select t.*
        , count(case when t.col='N' then 1 end) over(partition by t.id) as count_n
      from yourtable t
     ) d
where count_n >= 5

或子查询更传统的组

 select t.*, g.n
 from yourtable t
 inner join (
     select id, count(*) as n from yourtable y
     where y.col = 'N'
     group by id
     ) g on t.id = g.id
 where g.n >= 5

另一个是使用"内部连接横向"像这样

 select t.*, oa.n
 from yourtable t
 inner join lateral (
     select count(*) as n from yourtable y
     where y.id = t.id
     and y.col = 'N'
     ) oa on true
 where oa.n >= 5

SQLFiddle Demo