左边的两个表加入一个表,没有从连接中获取所有数据

时间:2018-03-07 15:23:39

标签: sql postgresql left-join

我有一个票据表:

tickets:
id       integer primary key
home_org varchar

有一个 homeorgs 表,其中包含所有家庭组织,并包含一个部门代码:

homeorgs:
home_org      varchar
division_code varchar

我希望能够显示每个部门每月的门票数量,即使特定部门尚未提交任何门票。对于没有票证的部门,我需要它显示0(零)。

这是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 

此sql不会引入未提交票证的homeorg行。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

只需删除“t.home_org is not null”即可阻止故障单表中不匹配的记录。

  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

答案 1 :(得分:0)

您的问题可能只是where条款。这是为查询的其他部分建议更简单的逻辑:

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 ;

就个人而言,我不会将年份和月份分成不同的列。我只是将日期截断到月初:

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 ;