I have a table structured like this:
| SchoolId | YearTerm | Submitted |
| ------------ | ------------ | ------------ |
| 1 | 2022-1 | 1 |
| 1 | 2022-2 | 1 |
| 1 | 2022-3 | 1 |
| 1 | 2022-4 | 1 |
| 2 | 2022-1 | 1 |
| 2 | 2022-2 | 1 |
| 2 | 2022-4 | 1 |
I am trying to figure out how many YearTerms these schools have been submitting in a row so I wrote some logic that gives me this output:
SchoolId | YearTerm | Submitted | SubmitOrder |
---|---|---|---|
1 | 2022-1 | 1 | 1 |
1 | 2022-2 | 1 | 2 |
1 | 2022-3 | 1 | 3 |
1 | 2022-4 | 1 | 4 |
2 | 2022-1 | 1 | 1 |
2 | 2022-2 | 1 | 2 |
2 | 2022-4 | 1 | 3 |
SELECT
G.*
,ROW_NUMBER() OVER( PARTITION BY SchoolId ORDER BY G.YearTerm ASC) SubmitOrder
FROM
(
SELECT
DISTINCT
SchoolId
,YearTerm
,1 Submitted
FROM Table
) G
The problem is that for schools that skip a YearTerm (in the picture above, SchoolId = 2 is getting credit for 3 consecutive submissions when in reality it should only be 2). The desired output I am looking for is:
SchoolId | YearTerm | Submitted | SubmitOrder |
---|---|---|---|
1 | 2022-1 | 1 | 1 |
1 | 2022-2 | 1 | 2 |
1 | 2022-3 | 1 | 3 |
1 | 2022-4 | 1 | 4 |
2 | 2022-1 | 1 | 1 |
2 | 2022-2 | 1 | 2 |
2 | 2022-4 | 1 | 1 |
Because SchoolId = 2 did not submit in 2022-3, there submission in 2022-4 is now there first submission in chronological order.
Any help is much appreciated!
Write a loop to solve for submissions consistency.
1条答案
按热度按时间y1aodyip1#
Something like this perhaps?
I check if current term follows the previous and if not, increments the "streak" group count. Then it's an easy ROW_NUMBER() that calculates where in the streak you are