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

MySQL : subtotals grouped by year

I have this table

+------------+---------+--------+
|       date |    item | amount |
+------------+---------+--------+
| 2022-01-12 | PA-1235 |    100 |
| 2022-01-07 | PA-1234 |     50 |
| 2022-01-07 |  RE-123 |     10 |
| 2021-12-22 | PA-1233 |    100 |
| 2021-11-21 | PA-1232 |    150 |
| 2021-11-15 |  RE-122 |     10 |
| 2021-11-13 |  RE-121 |     10 |
+------------+---------+--------+

I would like the total per year so I’ve done

SELECT YEAR(date) as year, SUM(amount) AS total FROM payments
GROUP BY YEAR(date) ORDER BY YEAR(date) DESC

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

+------+-------+
| year | total |
+------+-------+
| 2022 |   160 |
| 2021 |   270 |
+------+-------+

But know I’de like to have the subtotals for items starting with PA

+------+-----+-------+
| year |  PA | total |
+------+-----+-------+
| 2022 | 150 |   160 |
| 2021 | 250 |   270 |
+------+-----+-------+

UNION will add more lines, how to insert subqueries (item LIKE ‘PA-%’) in a single query?

I can’t change the table structure

>Solution :

SELECT YEAR(date) AS `year`, 
       SUM(CASE WHEN item LIKE 'PA-%'
                THEN amount
                ELSE 0 
                END) AS PA,
       SUM(amount) AS total 
FROM payments 
GROUP BY `year`
ORDER BY `year` DESC
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