1

长期潜伏者,第一次发帖,在过去的几周里,我一直在努力解决这个问题,这让我有点香蕉。

我有一张这样的桌子:

CREATE TABLE [dbo].[test_tbl](
[Company] [nvarchar](255) NULL,
[src_Amount] [float] NULL,
[src_FullDate] [date] NULL,
[src_ProjectedFromhRate] [decimal](18, 4) NULL,
[project_AgainstRate] [decimal](18, 4) NULL,
[ProjectedDate] [date] NULL,
[ProjectedAmount] [float] NULL) 

该表充满了如下信息:

INSERT INTO test_tbl VALUES ('Company 1', '2500', '2014-12-31', '0.0010', '-0.0050', '2015-01-31', '2487.50')
INSERT INTO test_tbl VALUES ('Company 1', '2600', '2014-12-31', '0.0020', '-0.0060', '2015-01-31', '2584.40')
INSERT INTO test_tbl VALUES ('Company 1', '2650', '2014-12-31', '0.0030', '-0.0070', '2015-01-31', '2631.45')
INSERT INTO test_tbl VALUES ('Company 2', '2500', '2014-12-31', '0.0010', '-0.0050', '2015-01-31', '2487.50')
INSERT INTO test_tbl VALUES ('Company 2', '2600', '2014-12-31', '0.0020', '-0.0060', '2015-01-31', '2584.40')
INSERT INTO test_tbl VALUES ('Company 2', '2650', '2014-12-31', '0.0030', '-0.0070', '2015-01-31', '2631.45')

我能够使用递归 CTE 为 2014-2018 之间的每个日期填充表格,这意味着每个月(2015-2018)都有一行,其他所有内容都相同。我想要做的是使用递归 CTE 来计算每个日期的金额。

我想根据上个月的 ((prevProjecteddateMonth.projectedAmount*project_AgainstRate) + prevProjectedDateMonth.projectedAmount) = 每个 src_ProjectedFromRate 和每个 project_AgainstRate 的每个公司从 2015 年到 2018 年的每一行的预计金额计算每个月的每个 ProjectedAmount。

到目前为止,我只能获得当年 2 月的费率,在过去两周内使用各种 CTE,老实说,这让我有点发疯,我想我会来看看你们中是否有人可以提供一些帮助。

非常感谢!

4

2 回答 2

1

除非我严重误解(可能),否则我认为您根本不需要 CTE。

select 
    Company,
    Src_Amount,
    src_ProjectedFromHRate,
    DATEADD(m, n.number, src_fulldate) as ProjectedDate,
    src_Amount * power(1+project_AgainstRate, number) as ProjectedValue
from test_tbl t,
    (Select * from master..spt_values where type='p' and number between 1 and 48) n
于 2013-10-13T09:36:49.373 回答
0

不确定我是否正确理解了这个问题,但这是我的尝试: http ://sqlfiddle.com/#!3/b8710/2

;with cte as
(
  select [Company]
  ,[src_Amount]
  ,[ProjectedDate] [src_FullDate]
  ,[src_ProjectedFromhRate]
  ,[project_AgainstRate]
  ,cast(DATEADD(d, -1,DATEADD(mm, DATEDIFF(m,0,[ProjectedDate]) + 2, 0)) as date) [ProjectedDate]
  ,[ProjectedAmount] 
  from test_tbl

  union all 

  select c.[Company]
  ,c.[src_Amount]
  ,c.[ProjectedDate]
  ,c.[src_ProjectedFromhRate]
  ,c.[project_AgainstRate]
  ,cast(DATEADD(d, -1,DATEADD(mm, DATEDIFF(m,0,c.[ProjectedDate]) + 2, 0)) as date)
  ,(c.[ProjectedAmount] * c.project_AgainstRate) + c.[ProjectedAmount] 
  from cte c
  where c.ProjectedDate < '2018-12-31'
)
insert test_tbl
select * 
from cte

select src_FullDate, Company, sum(ProjectedAmount) ProjectedAmount
from test_tbl
group by src_FullDate, Company
order by src_FullDate, Company
于 2013-10-13T00:38:33.637 回答