根据SQL Server中的日期范围将单行拆分为多行

问题描述 投票:0回答:1

我的SQL Server表结构如下所示

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

像这样,具有多种货币的历史汇率数据和超过3年的汇率,如上表所示,每种货币汇率的开始日期和结束日期都在1个月的范围内,我需要的是将其基本上划分为每一天,因此基本上需要每天汇率,例如:对于第一条记录,我需要30应将from_currency表示为EUR并将To_currency表示为GBP,将汇率表示为33.5的行以及新的date列应为从2018-03-31到2018-04-30的递增日期。

sql sql-server tsql date recursive-query
1个回答
0
投票

一个选项使用递归查询:

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

如果您的任何期间超过100天,则需要在查询末尾添加option(maxrecursion 0)

© www.soinside.com 2019 - 2024. All rights reserved.