I am trying to get max(level) and sum(hours) until someone reaches level 5 for the first time.
This is my input
date | level | hours |
---|---|---|
1/1/2021 | 1 | 1 |
1/2/2021 | 2 | 1 |
1/3/2021 | 2 | 2 |
1/4/2021 | 3 | 1 |
1/5/2021 | 4 | 1 |
1/6/2021 | 5 | 3 |
1/7/2021 | 5 | 1 |
1/8/2021 | 5 | 1 |
Output before the aggregate
date | level | hours |
---|---|---|
1/1/2021 | 1 | 1 |
1/2/2021 | 2 | 1 |
1/3/2021 | 2 | 2 |
1/4/2021 | 3 | 1 |
1/5/2021 | 4 | 1 |
1/6/2021 | 5 | 3 |
Final output
select max(level) as level, sum(hours) as total_hours
from final
level | hours |
---|---|
5 | 9 |
I am not sure how to use case statement with sum where I wanted to limit my data when it reached level 5 for the first time
This should calculate sum of hours if level is less than 5 as well
4
Answers
Assuming that your table has
id
column, here is the query:Condition
id <= (SELECT MIN(id) FROM table_name WHERE level = 5)
will restrict your data to a record where it reached level 5 for the first timeYou should try this
SELECT MAX(level), SUM(hours) FROM Table1 WHERE date <= (SELECT MIN(date) FROM Table1 WHERE level = 5 limit 1)
;SELECT MAX(level), SUM(hours) FROM Table1 WHERE date <= (SELECT MIN(date) FROM Table1 WHERE level = 5 limit 1) or date <= (SELECT MAX(date) FROM Table1 WHERE level < 5)
And – Maximum DATE required with Level < 5
DEMO
You can try this query this will works..
Result
Edited: If if the same hours occurred, then it will take the exact sum.