Postgresql 在一个查询中对不同的组进行计数

标签 postgresql

我需要计算每个城市、州和国家的计数。例如,如果我的表 T1 中有以下数据:

name      city  state   country
------------------------------
name1      c1     s1      C1
name2      c1     s1      C1
name3      c2     s1      C1
name4      c3     s1      C1
name5      c4     s2      C1
name6      c5     s2      C1
name7      c5     s3      C1
name8      c12    s12     C2

查询结果应为:

city    state    country   citycount, statecount, countrycount
-------------------------------------------------------------------
c1       s1        C1        2            4             7
c2       s1        C1        1            4             7
c3       s1        C1        1            4             7
c4       s2        C1        1            2             7
c5       s2        C1        1            2             7
c5       s3        C1        1            1             7
c12      s12       C2        1            1             1

如果我进行分组和计数,那么我需要编写 3 个不同的查询。但我想在一个查询中完成它。请帮忙。

最佳答案

您可以使用window functions ,例如,一种解决方案可能是这样的:

 SELECT DISTINCT city
    ,STATE
    ,country
    ,count(*) OVER (PARTITION BY city,STATE,country) AS citycount
    ,count(*) OVER (PARTITION BY STATE,country) AS statecount
    ,count(*) OVER (PARTITION BY country) AS countrycount
FROM T1
ORDER BY city
    ,STATE
    ,country

请看 fiddle here .

关于Postgresql 在一个查询中对不同的组进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306189/

相关文章:

python - SQLAlchemy 在 PostgresQL 中创建 View

sql - 如何计算数据库列中所有不同值的出现次数?

linux - PostgreSQL 10 从/etc 读取 postgresql.conf,但在/var 中指定数据目录

postgresql - PostgreSQL 事务 id (xmin) 是否按顺序出现在提交的版本中?

sql - 在 SQL 中选择到表中。它们是如何储存的?

java - 使用二进制传输时,准备好的语句中的文本数组返回 null

sql - 使用连接更新表,如果不存在则为 NULL

mysql - 如何在Mysql中同时更新不同的行

database - 创建 postgres 数据库的 docker 镜像?

c# - 无法选择最佳候选函数。您可能需要在 Postgres 中添加显式类型转换