简体   繁体   中英

two tables left join the one, not getting all the data from the join

I have a tickets table as this:

tickets:
id       integer primary key
home_org varchar

There is a homeorgs table that holds all the home organizations and includes a division code as this:

homeorgs:
home_org      varchar
division_code varchar

I want to be able to show number of tickets per month per division, even if a particular division has not submitted any tickets. For the division that have no tickets, I need it to show 0 (zero).

Here is the sql:

select 
       count(t.id) as ticket_count,
       to_number(to_char(t.submitdate,'MM'), '99') as mon,
       to_number(to_char(t.submitdate,'YYYY'), '9999') as yr,
       nd.division_key 
  from homeorgs as h 
       LEFT JOIN tickets as t
           ON t.home_org = h.home_org 
           and t.submitdate >= '2018-02-01 00:00:00'
           and t.submitdate <= '2018-02-28 23:59:59'
  where t.home_org is not null
 group by h.division_key, mon, yr
 order by yr, mon, h.division_key 

This sql does not bring in the homeorg rows in which no tickets have been submitted.

What am I doing wrong here?

Just remove the " t.home_org is not null" and this is preventing the unmatched records from the ticket table.

  select 
       count(t.id) as ticket_count,
       to_number(to_char(t.submitdate,'MM'), '99') as mon,
       to_number(to_char(t.submitdate,'YYYY'), '9999') as yr,
       nd.division_key 
  from homeorgs as h 
       LEFT JOIN tickets as t
           ON t.home_org = h.home_org 
           and t.submitdate >= '2018-02-01 00:00:00'
           and t.submitdate <= '2018-02-28 23:59:59'
 group by h.division_key, mon, yr
 order by yr, mon, h.division_key

Your problem is probably just the where clause. This is to suggest simpler logic for other parts of the query:

select count(t.id) as ticket_count,
       extract(month from t.submitdate) as mon,
       extract(year from t.submitdate) as yr,
       h.division_key 
from homeorgs h left join
     tickets as t
    on t.home_org = h.home_org and
       t.submitdate >= '2018-02-01' and
       t.submitdate < '2018-03-01'
group by h.division_key, mon, yr
order by yr, mon, h.division_key ;

Personally, I wouldn't split the year and month into different columns. I would just truncate the date to the beginning of the month:

select count(t.id) as ticket_count, date_trunc('month', t.submitdate) as yyyymm,
       h.division_key 
from homeorgs h left join
     tickets as t
    on t.home_org = h.home_org and
       t.submitdate >= '2018-02-01' and
       t.submitdate < '2018-03-01'
group by h.division_key, yyyymm
order by yyyymm, h.division_key ;

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.

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