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


37

编辑 Postgres 9.3

我正在处理具有以下架构的报告:http : //sqlfiddle.com/#!15/fd104/2

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

在此处输入图片说明

基本上它是一个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

一切正常之后,可以申请每小时和RPH,我可以自己修复

Answers:


74

如果我对您的理解正确,那么您正在寻找经过过滤的(有条件的)集合:

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;


对于旧版本(<9.4)进行编辑,您需要使用以下case语句:

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;

我正在使用9.3。可以吗
jackhammer013

@JoeneFloresca:不,对于9.3,您需要CASE声明。您应该始终指定要使用的版本,尤其是不是当前版本时。
a_horse_with_no_name

非常感谢!现在工作完美。抱歉,我编辑了我的帖子,下次再记住。谢谢:)
jackhammer013

链接到以下文档FILTERpostgresql.org/docs/current/static/…–
bcattle

对我有用(/)
萨耶耶夫
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.