[英]Aggregate rows to create new columns based off row content in MySQL
I currently have a query that returns this result:我目前有一个返回此结果的查询:
|product|status|
|-------|------|
|string1|A |
|string1|C |
|string2|B |
|string2|A |
|string3|B |
|string3|B |
----------------
And I would like to be able to convert it into a descriptive table like this.我希望能够将它转换成这样的描述表。
|product|total |A |B |C |
|-------|------|-----|-----|------|
|string1|2 |1 |0 |1 |
|string2|2 |1 |1 |0 |
|string3|2 |0 |2 |0 |
-----------------------------------
Is there some kind of rollup or handy function that lets me aggregate rows like this?是否有某种汇总或方便的功能可以让我像这样聚合行?
You want to pivot the data.您想对数据进行透视。 I would recommend conditional aggregation:我会推荐条件聚合:
select product, count(*) as total,
sum( status = 'A' ) as A,
sum( status = 'B' ) as B,
sum( status = 'C' ) as C
from (<your query here>) q
group by product;
In redshift and postgresql one should use在 redshift 和 postgresql 中,应该使用
select product, count(*) as total,
count(CASE WHEN status = 'A' THEN 1 END) as A,
count(CASE WHEN status = 'B' THEN 1 END) as B,
count(CASE WHEN status = 'C' THEN 1 END) as C
from (<your query here>) q
group by product;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.