The DB structure is as follow:
Addresses has many Plans Plans has many Jobs Jobs has many 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
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
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'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.