我目前有一个返回此结果的查询:
|product|status|
|-------|------|
|string1|A |
|string1|C |
|string2|B |
|string2|A |
|string3|B |
|string3|B |
----------------
我希望能够将其转换为这样的描述性表格。
|product|total |A |B |C |
|-------|------|-----|-----|------|
|string1|2 |1 |0 |1 |
|string2|2 |1 |1 |0 |
|string3|2 |0 |2 |0 |
-----------------------------------
是否有某种汇总或方便的功能让我汇总这样的行?
答案 0 :(得分:1)
您想要转动数据。我建议使用条件聚合:
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;
答案 1 :(得分:0)
在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;