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 group by with condition

I have a problem of MySQL group by. I have a field called ‘type’. I would like to make a group by of this field. Here is the examples.

Amount type
30 disable
50 V123
40 AGA
100 V2594
30 disable
40 school

I would like to have the following group by

type Amount
disable 60
VIP 150
AGA 40
school 40

which mean I would like to check if the type is ‘V’ for prefix. If it is ‘V’ prefix and the records will group together with new name ‘VIP’. Otherwise just keep the same name.

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

Thanks you a lot.

>Solution :

We can use conditional aggregation here:

SELECT
    CASE WHEN type LIKE 'V%' THEN 'VIP' ELSE type END AS type,
    SUM(Amount) AS amount
FROM yourTable
GROUP BY 1;
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