【问题标题】:Get data from a single table but treat it as two tables从单个表中获取数据但将其视为两个表
【发布时间】: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


【解决方案1】:

也可以使用 isnull 作为 id:

select isnull(cte1.wholeseller, cte2.wholeseller) as 'wholeseller'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多