Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: how to group years together

Tags:

sql

 'SELECT year, scores FROM database'

If my data looks something like

 year     score
 1901      100 
 1902      300
 1902      300
 1911      300
 1921      100
 .         .
 .         .
 .         .
 2000      

And I'm interested in looking at the years in groups of 10 and summing up their respective scores. So for years 1901 to 1910, the total score would be 700. For 1911 - 1920, it would be 300. How can I perform this in SQL?

like image 570
Adrian Avatar asked Dec 29 '25 10:12

Adrian


1 Answers

Depending on your actual DBMS something like this:

select cast( (year / 10) as integer) * 10 as year_group,
       sum(score)
from scores
group by year_group
order by year_group;

The above is ANSI SQL and will work on many DBMS. The cast() operator however is not supported by all DBMS in the same way, so the syntax for your DBMS might be slightly different.

SQLFiddle: http://sqlfiddle.com/#!15/7e4fb/1


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!