本文介绍了Postgres简单的“透视”表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的数据表
name | type | count
test | blue | 6
test2 | red | 3
test | red | 4
如何查询它以便得到表:
How can I query it such that I get a table:
name | num_red | num_blue
test | 4 | 6
test2 | 3 | 0
我当然可以选择count(*),其中type = blue等,但我不认为
I can of course select count(*) where type=blue etc but I can't think of how to count multiple types within one query like this.
谢谢!
推荐答案
您可以在选择子句中使用 CASE
。
You can use CASE
in you select clause.
SELECT name,
SUM(CASE WHEN type = 'red' THEN "count" ELSE 0 END) numred,
SUM(CASE WHEN type = 'blue' THEN "count" ELSE 0 END) numblue
FROM tableName
GROUP BY name
这篇关于Postgres简单的“透视”表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!