1

我目前正在处理 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 尝试了一些查询,但我迷路了。

有人能解释一下吗?

非常感谢

4

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 ║
╚═══════╩════════╝

这是一个带有演示的sqlfiddle 。

不过,您应该考虑在结果集中添加年份,否则您可以混合结果。

于 2013-06-17T18:45:53.807 回答
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

SQL Fiddle 与演示

如果您的数据不需要考虑这种情况,最好使用@Lamak 的简单解决方案。

于 2013-06-17T19:04:17.183 回答