我想获得两个日期之间的开始和结束日期之间的年份。假设如果我输入startdate为“ 07/06/2017”和结束日期为“ 18/09/2019”,我想列出其开始和结束之间的年份分别结束日期。请给我建议如何实现。
输入表:
BusinessRefId Period GoalType Amount StartDateUtc EndDateUtc Currency
Business B Year CommittedTransactionFee 18000 07/06/17 00:00 USD
输出表:
BusinessRefId Period GoalType Amount StartDateUtc EndDateUtc Currency
Business B 2019-2020 CommittedTransactionFee 18000 07/06/2019 07/06/2020 USD
Business B 2018-2019 CommittedTransactionFee 18000 07/06/2018 07/06/2019 USD
Business B 2017-2018 CommittedTransactionFee 18000 07/06/2017 07/06/2018 USD
我需要将日期拆分为几个月,即如果BusinessGoal.Period ='Month',并且我需要一个查询来根据BusinessGoal表中提及的“期间”以及输入和输出表中“ Year”和“ Year”和分别为“月”。输入表(BusinessGoal):
BusinessRefId Period GoalType Amount StartDateUtc EndDateUtc Currency
Business C Year CommittedTransactionFee 18000 05/07/19 00:00:00 19/09/19 00:00:00 USD
输出表(BusinessGoal):
BusinessRefId Period GoalType Amount StartDateUtc EndDateUtc Currency
Business C 2019-07 - 2019-08 CommittedTransactionFee 18000 05/07/2019 00:00:00 05/08/2019 00:00:00 USD
Business C 2019-08 - 2019-09 CommittedTransactionFee 18000 05/08/2019 00:00:00 05/09/2019 00:00:00 USD
Business C 2019-09 - 2019-10 CommittedTransactionFee 18000 05/09/2019 00:00:00 05/10/2019 00:00:00 USD
您需要一张数字表,在这里我使用最简单的数字
select BusinessRefId
, cast(ys.y as varchar(4)) + '-' + cast(ys.y + 1 as varchar(4)) Period
, GoalType, Amount
, dateadd(year, nmbs.n, tbl.StartDateUtc) StartDateUtc
, dateadd(year, nmbs.n + 1,tbl.StartDateUtc) EndDateUtc
, Currency
from
-- your real table here
(values (1, 'year', 'CommittedTransactionFee', 1800, cast('20160607' as date), cast (null as date), 'USD'))
tbl(BusinessRefId, Period, GoalType, Amount, StartDateUtc, EndDateUtc, Currency)
join
-- table of numbers
(values (0),(1),(2) --,..
) nmbs(n)
on dateadd(year, nmbs.n + 1, tbl.StartDateUtc) <= getdate()
cross apply (select Year(tbl.StartDateUtc) + nmbs.n y ) ys
编辑
请参见小提琴。这是我的查询的版本,其中包含有关需要哪些行(请注意ON
子句中的差异)以及如何计算结束日期的更多条件。它使用Soundappan的ddl和数据(扩展),可以令人满意地接近真实的ddl和数据。主要思想是相同的,使用数字表。您可能希望在数据库中实例化表以在其他类似查询中使用它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句