SQL Server Transpose to-date and from-date to consecutive calendar month increments

zdwk9cvp  于 2023-05-16  发布在  其他
关注(0)|答案(1)|浏览(130)

I have a table like this
| Person | Status | FromDate | ToDate |
| ------------ | ------------ | ------------ | ------------ |
| 1 | A | 2023-01-01 | 2023-03-31 |
| 1 | B | 2023-04-01 | 3999-12-31 |

I also have another balance table with aggregates on a monthly basis.

PersonValuePeriod
1value2023-01-01
1value2023-02-01
1value2023-03-01
1value2023-04-01
1value2023-05-01

What would be a smart way to join in the status values on a monthly increment so it appears as follows

PersonStatusPeriod
1A2023-01-01
1A2023-02-01
1A2023-03-01
1B2023-04-01
1B2023-05-01

Keen on thoughts!

I have tried some different joins but cant get it right. I am sure there is a smart way of doing this.

r1wp621o

r1wp621o1#

You can do it using inner join :

select t.Person, t.Status, b.Period
from mytable t
inner join balance b on b.Period between t.FromDate and t.ToDate

Result :

Person  Status  Period
1       A       2023-01-01
1       A       2023-02-01
1       A       2023-03-01
1       B       2023-04-01
1       B       2023-05-01

Demo here

相关问题