我有这个查询
SELECT NAME, OTHER_NAME, COUNT(NAME)
FROM ETHNICITY
GROUP BY NAME,OTHER_NAME
我想在该列上other_name
或name
该列中添加一个运行总和。
例如,如果有 3x 非裔美国人和 2x name= "other" 和 other_name = "jewish" 我想给它 3 和 2 作为计数并在遍历时将它们相加
有什么想法可以增加它以添加它吗?谢谢。
我更喜欢使用子查询来做到这一点:
select t.name, t.other_name, t.cnt,
sum(cnt) over (order by name) as cumecnt
from (SELECT NAME, OTHER_NAME, COUNT(NAME) as cnt
FROM ETHNICITY
GROUP BY NAME,OTHER_NAME
) t
这假设您需要按name
.
分析函数中的 order by 进行累积和。这是标准语法,Postgres 和 SQL Server 2012 也支持。
以下可能也有效
select name, other_name, count(name) as cnt,
sum(count(name)) over (order by name)
from ethnicity
group by name, other_name
我发现这更难阅读(sum(count())
有点刺耳)并且可能更容易出错。我没有在 Oracle 上尝试过这种语法;它在 SQL Server 2012 中工作。
sum() ... over()
在 Oracle 中,可以使用窗口函数轻松完成运行总和:
select name
, other_name
, name_count
, sum(name_count) over(
order by name, other_name) as running
from (
select name
, other_name
, count(name) as name_count
from ethnicity
group by
name
, other_name
order by
name
, other_name
) subqueryalias
查看分组集,让您汇总总数。
虽然不确定这是你所追求的......
SELECT NAME, OTHER_NAME, COUNT(NAME)
FROM ETHNICITY
GROUP BY GROUPING SETS ((NAME,OTHER_NAME), (Name), ())
抱歉 ID10T 错误...分组集不需要第二个聚合,计数将自行完成:
所以这个数据:
Name Other_Name
A B
A C
A D
B E
B F
B G
C H
C I
C J
结果是
Name Other_Name CNT(Name)
A B 1
A C 1
A D 1
A 3
B E 1
B F 1
B G 1
B 3
C H 1
C I 1
C J 1
C 3
9