繁体   English   中英

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

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

我的 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

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

一种选择使用递归查询:

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)

暂无
暂无

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

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