基于日期时间和唯一性的CTE的T-SQL投影/预测/计算问题

时间:2013-10-12 23:11:52

标签: sql sql-server database

长期潜伏着,第一次发布海报,过去几周我一直在努力解决这个问题,而且它已经让我有点香蕉了。

我有一张这样的表:

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)计算每个月的每个ProjectedAmount =每个src_ProjectedFromRate和每个project_AgainstRate的每个公司从2015年到2018年的每一行的预计金额

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

非常感谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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