1

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

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
4

4 回答 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()子句的原因。它被称为窗口函数

于 2013-10-08T10:59:07.810 回答
1
select
    tipe, sum(val), max(cnt) "total tipe"
from qwe
join (select count(distinct(tipe)) "cnt" from qwe) v on true
group by tipe
order by tipe

SQL-Fiddle 演示

于 2013-10-08T11:20:04.510 回答
1

这是一个奇怪的要求,但是,我建议您构建一个仅返回表的计数(tipe)的视图,然后加入该视图?我还没有测试过,但我很确定它会起作用。

于 2013-10-08T10:55:04.440 回答
0

您的查询给出了正确的输出。对于所需的输出,我不知道为什么您似乎需要将TOTAL TIPE值固定为 3 。

select tipe, sum(val), 3 as "total tipe" 
from qwe group by tipe order by tipe
于 2013-10-08T10:59:28.640 回答