Postgres计数在同一查询中具有不同的条件

时间:2015-09-01 07:54:31

标签: sql postgresql count inner-join

我正在制作一份包含以下架构的报告:http://sqlfiddle.com/#!15/fd104/2

当前查询工作正常,如下所示:

enter image description here

基本上它是一个3表内连接。我没有提出这个查询,但是离开它的开发人员我想修改查询。如您所见,TotalApplication只根据a.agent_id计算总申请数。您可以在结果中看到totalapplication列。我想要的是删除它并将totalapplication更改为新的两列。我想添加completedsurveypartitalsurvey列。所以基本上这部分将成为

SELECT a.agent_id as agent_id, COUNT(a.id) as CompletedSurvey
FROM forms a WHERE  a.created_at >= '2015-08-01' AND 
a.created_at <= '2015-08-31' AND disposition = 'Completed Survey'
GROUP BY a.agent_id

我刚刚添加了AND disposition = 'Completed Survey'但我需要partialsurvey的另一列与completedsurvey具有相同查询的唯一区别是

AND disposition = 'Partial Survey'

COUNT(a.id) as PartialSurvey

但我不知道在哪里放置查询或查询将如何。所以最终输出有这些列

agent_id, name, completedsurvey, partialsurvey, loginhours, applicationperhour, rph

一旦确定,那么applicationperhour和rph我可以自己修复

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您正在寻找过滤(条件)聚合:

SELECT a.agent_id as agent_id, 
       COUNT(a.id) filter (where disposition = 'Completed Survey') as CompletedSurvey, 
       count(a.id) filter (where disposition = 'Partial Survey') as partial_survey
FROM forms a 
WHERE a.created_at >= '2015-08-01' 
  AND a.created_at <= '2015-08-31' 
GROUP BY a.agent_id;

以上假设Postgres的当前版本(在撰写本文时为9.4)。对于旧版本(&lt; 9.4),您需要使用case语句,因为那里不支持filter条件:

SELECT a.agent_id as agent_id, 
       COUNT(case when disposition = 'Completed Survey' then a.id end) as CompletedSurvey, 
       COUNT(case when disposition = 'Partial Survey' then a.id end) as partial_survey
FROM forms a 
WHERE a.created_at >= '2015-08-01' 
  AND a.created_at <= '2015-08-31' 
GROUP BY a.agent_id;