从另一个给定输入的表中获取计数

时间:2015-06-29 21:32:02

标签: sql postgresql

我有3个表:filer_infofiler_persentpersent_email,通过以下方式连接:

filer_info.filer_info_id = filer_persent.filer_info_id
filer_persent.persent_info_id = persent_email.persent_info_id

我想在persent_email表中找到我有多个PRIMARY类型的所有行(即count> 1)。我想在查询中返回的唯一内容是filer_info.filer_ident和计数。

这给了我每一行,但我只想要返回行中filer_ident > 1的数据。

select * from filer_info f
inner join filer_persent fp on f.filer_info_id=fp.filer_info_id 
inner join persent_email p on fp.persent_info_id=p.persent_info_id
where fp.filer_persent_kind_cd = 'FILER' and     p.persent_email_kind_cd='PRIMARY'
order by f.filer_ident

1 个答案:

答案 0 :(得分:0)

SELECT  filer_ident, cnt
FROM    (
        SELECT  filer_info_id, COUNT(*) cnt
        FROM    filer_persent fp
        JOIN    persent_email p
        USING   (persent_info_id)
        WHERE   (fp.filer_persent_kind_cd, p.persent_email_kind_cd) = ('FILER', 'PRIMARY')
        HAVING  COUNT(*) > 1
        ) с
JOIN    filer_info f
USING   (filer_info_id)
WHERE   filer_ident > 1
ORDER BY
        f.filer_ident