[英]two tables left join the one, not getting all the data from the 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行。
我在这里做错了什么?
只需删除“ t.home_org不为空”,这可以防止票证表中的记录不匹配。
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
您的问题可能只是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 ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.