SQL Server 2008 查询正向现金流报告
Posted
技术标签:
【中文标题】SQL Server 2008 查询正向现金流报告【英文标题】:SQL Server 2008 query for forward cash flow report 【发布时间】:2013-06-17 18:22:44 【问题描述】:我目前正在处理 s-s-rS 报告,该报告应显示用户定义期间的估计现金流量,例如:提前 1 年
我的表格如下所示:
ID DepositDate DepositAmt BalanceDueDate TotalAmount
--------------------------------------------------------
1 02/06/2011 10% 02/07/2011 100
2 16/06/2011 10% 16/07/2011 200
3 08/07/2011 20% 08/08/2011 300
4 15/07/2011 10% 15/08/2011 400
过程
Month Amount
-------------
06 10 (10% (deposit %) of Total amount for ID 1)
06 20 (10% of Total amount for ID 2)
07 90 (balance amount after deposit from previous month for ID 1)
07 180 (balance amount after deposit from previous month for ID 2)
07 60 (20% of Total amount for ID 3)
07 40 (10% of Total amount for ID 4)
08 240 (balance amount after deposit from previous month for ID 3)
08 360 (balance amount after deposit from previous month for ID 4)
预期输出
Month Amount
-------------
06 30
07 370
08 600
用 CTE 尝试了一些查询,但我迷路了。
有人能解释一下吗?
非常感谢
【问题讨论】:
存款和余额之间的差距总是一个月吗?我们是否可以假设它总是一个月的同一天,即 2 日的存款将有 2 日的余额? 不,两个日期之间的间隔可能会有所不同。 【参考方案1】:给你:
SELECT [Month],
SUM(Amount) Amount
FROM ( SELECT MONTH(DepositDate) [Month],
DepositAmt * TotalAmount Amount
FROM YourTable
UNION ALL
SELECT MONTH(BalanceDueDate),
TotalAmount * (1 - DepositAmt)
FROM YourTable) A
GROUP BY [Month]
ORDER BY [Month]
结果:
╔═══════╦════════╗
║ Month ║ Amount ║
╠═══════╬════════╣
║ 6 ║ 30 ║
║ 7 ║ 370 ║
║ 8 ║ 600 ║
╚═══════╩════════╝
Here is a sqlfiddle 带有演示。
不过,您应该考虑在结果集中添加年份,否则您可能会混淆结果。
【讨论】:
太棒了!我会试一试。感谢您对包含年份的建议。【参考方案2】:这是一个可以处理多个月的周期:
with CashMovements as
(
select *
, CashMovement = DepositAmt * TotalAmount
, CashPaid = DepositAmt * TotalAmount
from Deposits
union all
select ID
, dateadd(mm,1,DepositDate)
, DepositAmt
, BalanceDueDate
, TotalAmount
, CashMovement = case when dateadd(Month,1,DepositDate) >= BalanceDueDate
then TotalAmount - CashPaid
else DepositAmt * TotalAmount
end
, CashPaid = case when dateadd(mm,1,DepositDate) >= BalanceDueDate
then CashPaid + (DepositAmt * TotalAmount)
else 0.0
end
from CashMovements
where dateadd(Month,1,DepositDate) <= BalanceDueDate
)
select Month = Month(DepositDate)
, Amount = sum(CashMovement)
from CashMovements
group by Month(DepositDate)
order by Month
SQL Fiddle with demo.
如果您的数据不需要考虑这种情况,最好使用@Lamak 的简单解决方案。
【讨论】:
以上是关于SQL Server 2008 查询正向现金流报告的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server 2008 R2-查询以获取按月销售的总销售额和数量
SQL Server 2008 R2 / s-s-rS 2008:服务水平报告创建
列出 SQL Server 2008 R2 中的所有数据源及其依赖项(报告、项目等)
SQL Server 2008 R2 Performance Studio - 数据收集工作但查看报告抛出“连接失败...”18456 错误