sql - 条件为 "group By"的总行

标签 sql postgresql

我在查询中遇到问题。我使用的是 postgresql。我需要获得总行,但条件是“分组依据”

table qwe 
----------------------------
TIPE   | VAL
----------------------------
1      | 2
2      | 3 
2      | 1
2      | 4
3      | 1
3      | 3

我需要的结果是

-------------------------
TIPE   | VAL | TOTAL TIPE
-------------------------
1      | 2   | 3
2      | 8   | 3
3      | 4   | 3

到目前为止我尝试过的查询

select tipe, sum(val), count(tipe) "total tipe" 
from qwe group by tipe order by tipe


-------------------------
TIPE   | VAL | TOTAL TIPE
-------------------------
1      | 2   | 1
2      | 8   | 3
3      | 4   | 2

最佳答案

你可以试试这个:

select
    tipe, sum(val), count(tipe) over() as "total tipe"
from qwe
group by tipe
order by tipe

sql fiddle demo

您看,您可以计算整个结果集中非空记录的数量,而不是计算每个组中非空 tipe 记录的数量 - 这就是您需要 over() 的原因 子句。它叫做window functions .

关于sql - 条件为 "group By"的总行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19245718/

相关文章:

sql - 在postgres中的单个表上查询多行和多列

mysql - 具有关系的计数表 vb.net

sql - 单个列的多个外键

MySQL 多行,对多个值进行分组

php - 使用 codeigniter 和 postgresql foreach() 将不同表中的 2 个值相乘

python - 如何创建包含不同类型的查询集表达式

postgresql - 在 Postgresql 中创建分区表

sql - postgres 中 SQL 以外的语言

mysql - group-concat问题,结果不对

PostgreSQL 9.5 : Exception handling