我目前正致力于SSRS报告,该报告应显示用户定义期间的估计现金流量,例如:提前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的一些疑问,但我迷路了。
任何人都能解释一下吗?
非常感谢
答案 0 :(得分: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 ║
╚═══════╩════════╝
带有演示的
您应该考虑在结果集上添加年份,否则您可以混合结果。
答案 1 :(得分:1)
这是一个可以处理多个月的时间段:
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
如果您的数据不需要考虑这种情况,最好使用@Lamak的简单解决方案。