简体   繁体   中英

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

my SQL server table structure is some what like below

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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