子查询上的多个ID用于计算计数

时间:2018-06-12 00:24:30

标签: sql postgresql

我有这个问题:

select count(*) as num_valid_admins
from (select distinct on (ad.admin_id) ad.*
     from admin_descriptions ad
     where ad.description_id = XXX
     order by ad.admin_id, ad.valid_at desc
    ) ad
where ad.value is not null;

成功获得了description_id,它为我提供了使用该描述的管理员数量。只要admin_descriptions表中有一行description_id,NOT NULL值且valid_at比任何其他条目最新,就会考虑使用admin的说明。该NULL的值为description_id

所以,对于这种类型的数据:

Row 1:
description_id: 1
value: 'foo'
admin_id: 2
valid_at: '2010-01-10'

Row 2:
description_id: 1
value: NULL
admin_id: 2
valid_at: '2012-01-10'

Row 2:
description_id: 1
value: 'some value'
admin_id: 4
valid_at: '2014-01-10'

查询description_id = 1时的计数为1.它只考虑第3行。因为即使存在值为NOT NULL的第一行,还有第2行valid_at更多最近是相同的admin_id,其值为NULL。

现在,我正在尝试修改查询,以便我可以查询多个description_ids,但我无法弄清楚如何修改查询。我想要的是一组看起来像description_id, count

的结果

我尝试过像这样修改内部查询:

select count(*) as num_valid_admins
from (select distinct on (ad.admin_id) ad.*
     from admin_descriptions ad
     where ad.description_id IN (x,y,z)
     order by ad.admin_id, ad.valid_at desc
    ) ad
where ad.value is not null
GROUP BY ad.description_id

但是并没有按description_id向我回复计数。

1 个答案:

答案 0 :(得分:1)

您需要将说明ID添加到order bydistinct on

select ad.description_id, count(*) as num_valid_admins
from (select distinct on (ad.description_id, ad.admin_id) ad.*
     from admin_descriptions ad
     where ad.description_id IN (x, y, z)
     order by ad.description_id, ad.admin_id, ad.valid_at desc
    ) ad
where ad.value is not null
group by ad.description_id;