返回符合条件的分组记录列的计数

  • 本文关键字:记录 条件 返回 postgresql
  • 更新时间 :
  • 英文 :


我有一个名为watched_url_scan_result的表,它有一列watched_url_scan_status

它;s的目的是存储watched_url_record表中每个条目的扫描结果。

我想做的是创建一个查询,为watched_url_record表中的每个记录提供watched_url_scan_status中出现的每种状态类型的计数。

我试过了:

select count(wusr.watched_url_scan_status = 'NotFound') NotFound, count(wusr.watched_url_scan_status = 'Found') Found, * from watched_url_scan_result wusr
join watched_url_record wur on wusr.watched_url_record_id = wur.id
where wur.user_auth_custom_id = 4
group by wusr.id, wur.id

但无论我试图将状态匹配到哪个字符串,它总是显示计数为1。我知道我离我的方法很远,有人能给我指正确的方向吗?

尝试此查询:

select wur.id, count(wusr.watched_url_scan_status = 'NotFound') NotFound, count(wusr.watched_url_scan_status = 'Found') Found
from watched_url_scan_result wusr
join watched_url_record wur on wusr.watched_url_record_id = wur.id
where wur.user_auth_custom_id = 4
group by wur.id

如果希望只显示NotFoundFound的行,则可以添加HAVING子句。

count统计所有非NULL。'true和false都不为NULL。

您可以应用FILTER:

select 
count(*) filter (where wusr.watched_url_scan_status = 'NotFound') NotFound, 
count(*) filter (where wusr.watched_url_scan_status = 'Found') Found,
wur.* 
from watched_url_scan_result wusr
join watched_url_record wur on wusr.watched_url_record_id = wur.id
where wur.user_auth_custom_id = 4
group by wur.id

最新更新