MySQL group by with condition

q8l4jmvw  于 2022-12-22  发布在  Mysql
关注(0)|答案(1)|浏览(153)

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.
Thanks you a lot.

8ftvxx2r

8ftvxx2r1#

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;

相关问题