简体   繁体   English

根据 sql 服务器中的日期范围将单行拆分为多行

[英]Split a single row into multiple rows based on date range in sql server

my SQL server table structure is some what like below我的 SQL 服务器表结构如下所示

FROM_Currency   To_Currency   ExchangeRate   StartDate    EndDate
EUR               GBP            33.5        2018-03-31    2018-04-30
USD               EUR            22.9        2019-01-31    2019-02-28

like this have historical exchange rate data for multiple currencies and exchange rate for over 3 years, as shown in above table we have start date and enddate for each currency rate in a range of 1 month,what i need is to basically split it into each day,so basically need exchange rate daily,for ex: for 1st record i need 30 rows which should say from_currency as EUR and To_currency as GBP and exchange rate as 33.5 and new date column should be increment date starting from 2018-03-31 to 2018-04-30.像这样有多种货币的历史汇率数据和超过 3 年的汇率,如上表所示,我们有 1 个月范围内每种货币汇率的开始日期和结束日期,我需要基本上将其拆分为每个一天,所以基本上每天都需要汇率,例如:对于第一条记录,我需要 30 行,其中应该说 from_currency 为 EUR,To_currency 为 GBP,汇率为 33.5,新日期列应该是从 2018 年 3 月 31 日开始的递增日期到2018-04-30。

One option uses a recursive query:一种选择使用递归查询:

with cte as (
    select 
         from_currency, 
         to_currency, 
         exchange_rage, 
         startDate, 
         endDate, 
         startDate currentDate
    from mytable t
    union all
    select 
         from_currency, 
         to_currency, 
         exchange_rage, 
         startDate, 
         endDate, 
         dateadd(day, 1, currentDate)
    from cte
    where currentDate < endDate
)
select from_currency, to_currency, exchange_rage, currentDate from cte

If your any of your periods span over more 100 days, then you need to add option(maxrecursion 0) at the end of the query.如果您的任何时期跨越 100 天以上,那么您需要在查询末尾添加option(maxrecursion 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM