简体   繁体   English

MySQL 按条件分组

[英]MySQL group by with condition

I have a problem of MySQL group by.我有一个 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 30 disable禁用
50 50 V123 V123
40 40 AGA AGA
100 100 V2594 V2594
30 30 disable禁用
40 40 school学校

I would like to have the following group by我想有以下组

type类型 Amount数量
disable禁用 60 60
VIP贵宾 150 150
AGA AGA 40 40
school学校 40 40

which mean I would like to check if the type is 'V' for prefix.这意味着我想检查前缀类型是否为“V”。 If it is 'V' prefix and the records will group together with new name 'VIP'.如果是“V”前缀,记录将与新名称“VIP”组合在一起。 Otherwise just keep the same name.否则就保持相同的名称。

Thanks you a lot.非常感谢你。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM