简体   繁体   English

SQL如何在以下情况下联接两个表以获取记录?

[英]SQL How to join two tables to get records in following scenario?

Payments 支付

Year     Month       Division       Department   Payments_received_Count
------------------------------------------------------------------------
2016       1           Electric      dep1         2
2016       1           Electric      dep2         3
2015       1           Electric      dep1         1

Divisions 分部

Division             Department   
--------------------------------
Electric             Dep1                      
Electric             Dep2                 
Electric             Dep3        

How to join the tables to get the following result? 如何联接表以获得以下结果?

Year     Month       Division       Department   Payments_received_Count
------------------------------------------------------------------------
2016       1           Electric      dep1         2
2016       1           Electric      dep2         3
2016       1           Electric      dep3         0
2015       1           Electric      dep1         1
2015       1           Electric      dep2         0
2015       1           Electric      dep3         0

So for each year and month I have to join the payments table with division table. 因此,对于每一年和每个月,我都必须将付款表与部门表结合起来。 Please suggest an approach. 请提出一种方法。

I know CASE WHEN will help in this scenario, but I have not been able to find the right way. 我知道CASE WHEN在这种情况下会有所帮助,但我一直找不到正确的方法。

CASE Payments_received_Count
     WHEN null THEN 0
     ELSE Payments_received_Count

Thanks 谢谢

You need a combination of division/department and year/month. 您需要部门/部门和年/月的组合。 First, generate the rows using cross join . 首先,使用cross join生成行。 Then use left join to get the values: 然后使用left join获取值:

select ym.year, ym.month, d.division, d.department,
       coalesce(Payments_received_Count, 0) as Payments_received_Count
from divisions d cross join
     (select distinct year, month from payments) ym left join
     payments p
     on d.division = p.division and d.department = p.department and
        ym.year = p.year and ym.month = p.month
order by year desc, month desc, division, department;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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