【发布时间】:2016-01-08 04:25:55
【问题描述】:
我有这张桌子:
会计分录
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
wholeseller 为 NULL,因为在第一个表 cte1 中,在 FromDate 之前没有记录。你能告诉我如果第一个表 cte1 中没有记录,wholeseller 不会为 NULL 怎么做,然后只使用第二个表 cte2 中的 WholesellerId 吗?当我使用 LEFT JOIN 而不是 FULL JOIN 时,也会发生同样的事情。
【问题讨论】:
-
您只需要一行吗?
-
它可以有尽可能多的行,具体取决于 WholeSellerId 的数量。但是,每个 WholeSellerId 应该只有 1 个结果。
标签: sql-server