计算查询结果的行数

时间:2014-02-04 18:19:41

标签: sql

想要计算聚合查询结果中的记录。因此,如果我的原始数据如下所示:

========================
Field 1 Field 2 Field 3
------------------------
aaa ccc 10
aaa ccc 10
aaa ddd 10
aaa ddd 10
bbb ddd 10
bbb ddd 10
bbb eee 10

我按字段1,字段2和字段3的总和进行分组 所以结果看起来:

========================
Field 1 Field 2 Field 3
------------------------
aaa ccc 20
aaa ddd 20
bbb ddd 20
ddd eee 10

我想算一下,每个值出现在Field 1和Field 2中的次数。

所以结果看起来像这样:

======================================================
Field 1 Field 2 Field 3 Count Field 1   Count Field 2
------------------------------------------------------
aaa ccc 20  2   1
aaa ddd 20  2   2
bbb ddd 20  2   2
ddd eee 10  2   1

我尝试使用Cound函数,但它计算原始表,所以显示原始表的结果,我得到结果:

======================================================
Field 1 Field 2 Field 3 Count Field 1   Count Field 2
------------------------------------------------------
aaa ccc 20  4   2
aaa ddd 20  4   4
bbb ddd 20  3   4
ddd eee 10  3   1

1 个答案:

答案 0 :(得分:0)

大多数数据库都支持窗口/分析功能。这些可以在聚合中组合以执行您想要的操作:

select field1, field2, sum(field3) as sumfield3,
       count(*) over (partition by field1) as numField1,
       count(*) over (partition by field2) as numField2
from table t
group by tield1, field2;