我有这个问题:
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
向我回复计数。
答案 0 :(得分:1)
您需要将说明ID添加到order by
和distinct 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;