我有这张桌子:
AccountingEntry
ID | DateAdded | Credit | Debit | Collections | Withdrawal | WholeSellerId
1 | 2016-01-08| 1000.00| 0.00 | 0.00 | 0.00 | Sample1
2 | 2016-01-08| 0.00 | 200.00| 0.00 | 0.00 | Sample1
3 | 2016-01-08| 0.00 | 0.00 | 300.00 | 0.00 | Sample1
4 | 2016-01-08| 0.00 | 0.00 | 0.00 | 500.00 | Sample1
5 | 2016-01-08| 300.00 | 0.00 | 0.00 | 0.00 | AnotherSample
6 | 2016-01-08| 0.00 | 200.00| 0.00 | 0.00 | AnotherSample
我想要实现的是获得目前的问责制和以前的问责制。 "现在的责任"是:从FromDate到ToDate 以及之前的问责制"是:在FromDate之前添加的任何总和。
我有这样的声明:
with
cte1 as
(select ae1.WholeSellerId as 'wholeseller', isnull((sum(isnull(ae1.Withdrawals,0)) + sum(isnull(ae1.Credit,0))) - (sum(isnull(ae1.Debit,0)) + sum(isnull(ae1.Collections,0))),0) as 'previous_accountability'
from AccountingEntry ae1
where ae1.DateAdded < '2016-01-08'
group by WholeSellerId),
cte2 as
(select ae2.WholeSellerId as 'wholeseller2', isnull((sum(isnull(ae2.Withdrawals,0)) + sum(isnull(ae2.Credit,0))) - (sum(isnull(ae2.Debit,0)) + sum(isnull(ae2.Collections,0))),0) as 'present_accountability'
from AccountingEntry ae2
where ae2.DateAdded between '2016-01-08' and '2016-01-09'
group by WholeSellerId)
select cte1.wholeseller as 'wholeseller', isnull(cte1.previous_accountability,0) as 'previous accountabiliy', isnull(cte2.present_accountability,0) as 'present accountability'
from cte1
full join cte2 on cte1.wholeseller=cte2.wholeseller2
结果如下:
wholesellerId | previous accountability | present accountability
NULL | 0.00 | 1000
NULL | 0.00 | 100
整个商家是NULL,因为在第一个表cte1中,FromDate之前没有记录。如果在第一个表cte1中没有记录,那么你能告诉我怎么做整个卖家不会是NULL,然后在第二个表cte2中使用fullsellerId吗?当我使用 LEFT JOIN 而不是 FULL JOIN 时,会发生同样的事情。
答案 0 :(得分:1)
也可以使用isnull作为id:
select isnull(cte1.wholeseller, cte2.wholeseller) as 'wholeseller'