仅当组中的所有记录都符合条件

时间:2016-06-09 05:43:17

标签: sql postgresql

数据库结构如下:

地址有很多计划 计划有很多工作 乔布斯有很多UserJobs

我试图将针对特定地址完成的所有工作分组,而不管计划如何。

从那里我只想看到没有完成一项成功工作的地址

成功的工作是UserJobs.perfomance = ontime或UserJobs.perfomance = late

SELECT
  "addresses"."address1",
  "user_jobs"."performance"

FROM
  "addresses" JOIN "plans" ON "addresses"."id" = "plans"."address_id" 
  JOIN "jobs" ON "plans"."id" = "jobs"."plan_id" 
  JOIN "user_jobs" ON "jobs"."id" = "user_jobs"."job_id"

group by   
  "addresses"."address1",
  "user_jobs"."performance"

我尝试构建上面的查询,但我已经可以看到它的缺陷。它将按地址分组,但如果该地址内有不同的性能,它将分开

2 个答案:

答案 0 :(得分:1)

如果要计算成功完成工作,可以使用条件聚合

SELECT
  "addresses"."address1",
  COUNT(CASE 
           WHEN "user_jobs"."performance" IN ('ontime', 'late') THEN 1
        END) AS cnt  
FROM
  "addresses" JOIN "plans" ON "addresses"."id" = "plans"."address_id" 
  JOIN "jobs" ON "plans"."id" = "jobs"."plan_id" 
  JOIN "user_jobs" ON "jobs"."id" = "user_jobs"."job_id"    
GROUP BY   
  "addresses"."address1

答案 1 :(得分:1)

"组中的所有记录都符合标准" - > bool_and聚合函数

select "addresses"."address1" FROM
    "addresses" JOIN "plans" ON "addresses"."id" = "plans"."address_id" 
    JOIN "jobs" ON "plans"."id" = "jobs"."plan_id" 
    JOIN "user_jobs" ON "jobs"."id" = "user_jobs"."job_id"

   group by   
     "addresses"."address1"
   HAVING bool_and("user_jobs"."performance" IN ('ontime', 'late'))