I have a table as shown below with year and quantity of goods sold in each year, I want to group the year column into ranges of Decades and sum the quantity sold in each decade. Having in mind that the First decade is 1980 - 1989, Second decade is 1981 - 1990, so on... The expected result is also shown in the second table below
sample: expected_result:
+------+----------+ +-----------+------------+
| year | qty | | Decades | Total_qnty |
+------+----------+ +-----------+------------+
| 1980 | 2 | | 1980-1989 | 13 |
| 1981 | 1 | | 1981-1990 | 12 |
| 1983 | 8 | | 1982-1991 | 12 |
| 1989 | 2 | | 1983-1992 | 12 |
| 1990 | 1 | | . | . |
| 1992 | 1 | | . | . |
| 1994 | 4 | | . | . |
+------+----------+ +-----------+------------+
Below is the sample code I tried with a couple of others but the result is not as expected,
SELECT t.range AS Decades, SUM(t.qty) as Total_qnty
FROM (
SELECT case
when s.Year between 1980 and 1989 then '1980 - 1989'
when s.Year between 1981 and 1990 then '1981 - 1990'
when s.Year between 1982 and 1991 then '1982 - 1991'
when s.Year between 1983 and 1992 then '1983 - 1992'
else '1993 - above'
end as range, s.qty
FROM sample s) t,
group by t.range
I tried this and this but still could not get the expected result. Also I wouldn't want to hardcode things. Please any help will be appreciated.