SQL如何在以下场景中连接两个表以获取记录?

时间:2015-12-29 00:46:14

标签: sql sql-server

付款

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

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

如何加入表格以获得以下结果?

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

因此,对于每年和每月,我必须使用分部表加入付款表。请提出一个方法。

我知道CASE WHEN会在这种情况下有所帮助,但我找不到正确的方法。

CASE Payments_received_Count
     WHEN null THEN 0
     ELSE Payments_received_Count

由于

1 个答案:

答案 0 :(得分:2)

您需要部门/部门和年/月的组合。首先,使用ScrollArea生成行。然后使用cross join获取值:

left join