[英]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.