简体   繁体   English

仅当组中的所有记录均符合条件时才分组并返回结果

[英]Grouping and returning result only when all records in the group match the criteria

The DB structure is as follow: 数据库结构如下:

Addresses has many Plans Plans has many Jobs Jobs has many UserJobs 地址有很多计划计划有很多工作职位有很多UserJobs

I'm trying to group all the Jobs done for an specific Address regardless of the Plan. 我试图将针对特定地址完成的所有工作归为一组,而不管计划如何。

From there I would only want to see the Addresses that have not had a single successful work done 从那里,我只想看到尚未完成一项成功工作的地址

A successful work is when UserJobs.perfomance = ontime or UserJobs.perfomance = late 成功的工作是当UserJobs.perfomance =准时或UserJobs.perfomance =晚

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"

I tried building the query above but I can already see the flaw in it. 我尝试构建上面的查询,但是我已经看到了它的缺陷。 It will group by address but if there are different performances within that address it will split 它将按地址分组,但如果该地址内有不同的演奏,它将拆分

You can use conditional aggregation if you want to count successful work done: 如果要统计已完成的工作,可以使用条件聚合

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

"all records in the group match the criteria" -> bool_and aggregate function “组中的所有记录均符合条件”-> 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'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM