Here is a simplified example of what my output currently looks like:
| Name | Month | Year | Filter | Data |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| Bob | Feb | 2018 | Good! | 10 |
| Bob | Apr | 2018 | Bad | 0 |
| Tom | Dec | 2019 | Good! | 5 |
| Tom | Feb | 2020 | Bad | 0 |
| Sam | Feb | 2018 | Good! | 2 |
| Sam | Apr | 2018 | Bad | 0 |
| Tim | Oct | 2022 | Good! | 50 |
| Tim | Jan | 2023 | Bad | 0 |
My Goal: I'm trying to duplicate any record and apply new months to it if my filter = Good! Within my data, there is gaps between months and I need to have everything in sequential order by month until my filter = bad. Ultimately I need for my output to look like this:
Name | Month | Year | Filter | Data |
---|---|---|---|---|
Bob | Feb | 2018 | Good! | 10 |
Bob | Mar | 2018 | Good! | 10 |
Bob | Apr | 2018 | Bad | 0 |
Tom | Dec | 2019 | Good! | 5 |
Tom | Jan | 2020 | Good! | 5 |
Tom | Feb | 2020 | Bad | 0 |
Sam | Feb | 2018 | Good! | 2 |
Sam | Mar | 2018 | Good! | 2 |
Sam | Apr | 2018 | Bad | 0 |
Tim | Oct | 2022 | Good! | 50 |
Tim | Nov | 2022 | Good! | 50 |
Tim | Dec | 2022 | Good! | 50 |
Tim | Jan | 2023 | Bad | 0 |
Here is what SQL output looks like exactly: enter image description here here I am grouping by LotSysID, VehicleMainSysID, Month Number, YearNumber, and Description. Instead of name in my example output, I am using VehicleMainSysID and LotSysID. Instead of Filter I am using description, bad = Transferred. Good=Retail Inventory.
Essentially, I have data from 2018 up until now and I need to include any gaps of months for when filter = Good! until it equals Bad. There may not even be an additional row where filter = bad, in those cases I would just need to have the data continue to be duplicated until this current month for this current year. NOTE: there is no set start date where all the data begins, depending on the name, the data can start in any month between years 2018-current. I need a dynamic statement where I can create additional rows to fit my business logic.
I've thought of using a recursive statement but was told that it would be incredibly taxing on our server since I'm pulling millions of records through my query.
1条答案
按热度按时间pengsaosao1#
Here's one way that finds first month and last month (when the last month has
'Bad'
) for each name, then joins that to a list of all months from the earliest date in the data until today, then usesOUTER APPLY
to find the previous value to determine what to fill the gaps with.Working example in this db<>fiddle - including the edge case where a person's latest
Filter = 'Good'
.Output: