Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL IFELSE Statement To create Sum Variable

TABLE 1     
STUDENT TIME    SCORE
1   1   4
1   2   3
1   3   4
2   1   2
2   2   2
2   3   8
3   3   10
3   4   10
4   1   1
4   2   3
4   3   2
4   4   4
4   5   4
4   6   5

I have TABLE 1. I wish to group and SUM(SCORE) for each STUDENT and TIME 1-2, 3-4, 5-6 to create this TABLE 2

STUDENT TIME    TOTALSCORE
1   1-2 7
1   3-4 4
1   5-6 NA
2   1-2 4
2   3-4 8
2   5-6 NA
3   1-2 NA
3   3-4 20
3   5-6 NA
4   1-2 3
4   3-4 6
4   5-6 4

However I have BIG DATA so Wish to start by doing this

select DISTINCT(TIME) from TABLE1
1
2
3
4
5
6

and then basically take all TIME values >= 1 & < 2 as T1; >=2 & < 3 as T2; it matters because we use #.# where the first # is the year and the second # is the trimester. So there are values such as 1.1, 1.2, 1.3 but I don’t wish to list that out all the time

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EDIT

    TABLE 1     
STUDENT TIME_STAMP  SCORE   TIME_MESTER
1   2021-11-30  4   2020-01-01
1   2021-10-02  3   2020-05-31
1   2021-04-11  4   2020-08-30
2   2021-01-24  2   2020-12-31
2   2021-03-18  2   2021-01-01
2   2020-02-01  8   2021-05-31
3   2021-05-02  10  2021-08-30
3   2021-02-10  10  2021-12-31
4   2020-07-10  1   NA
4   2020-08-04  3   NA
4   2020-07-13  2   NA
4   2020-05-28  4   NA
4   2020-04-01  4   NA
4   2021-07-01  5   NA

>Solution :

Using integer math we can use (time-1)/2 to give us groups of all times between 1-2, 3-4, 5-6, 7-8 etc.

select   student
        ,sum(score) as total_score
        ,concat((time+1)/2*2-1, '-', (time+1)/2*2) as semester
from     t
group by student, (time+1)/2
order by student
student total_score semester
1 7 1-2
1 4 3-4
2 4 1-2
2 8 3-4
3 20 3-4
4 4 1-2
4 6 3-4
4 9 5-6

Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading