I'm having hard times with a PostgreSQL SELECT that at first looked pretty simple. Involved tables:
CREATE TABLE events (id INT, customers_id INT);
CREATE TABLE jobs (
  events_id INT,
  "from"    TIMESTAMP,
  until     TIMESTAMP,
  users_id  INT);
- each event can have multiple jobs
- start and end of an event is defined by the lowest "from"and the highestuntilof the corresponding jobs
- each job can be assigned to a user
I need a table like the following:
events_id | customers_id | min(from) | max(until) | total_jobs | open_jobs
        1 |            1 |  .. 08:00 |   .. 11:00 |          4 |        1
My select so far:
SELECT e.id, e.customers_id, min(j.from) as min_from, max(j.until) as max_until, 
  count(j.id) as total_jobs
FROM events e
LEFT JOIN jobs j ON j.events_id = e.id
GROUP BY e.id, e.customers_id
This gives me the result for the first 5 columns, but how can I include a second count for just the jobs with users_id = NULL? I would assume that I need a second LEFT JOIN on the jobs table but somehow I can't get it working.
How can I implement that correctly and efficiently?
 
     
     
    