我有这个查询
SELECT NAME, OTHER_NAME, COUNT(NAME)
FROM ETHNICITY
GROUP BY NAME,OTHER_NAME
我希望在该列的other_name
或name
上添加一笔运行金额。
例如,如果有3x非洲裔美国人和2x名称=“其他”和其他名称=“犹太人” 我想给它3和2作为计数并在它遍历时总结它们
我有什么想法可以增加这一点吗?谢谢。
答案 0 :(得分: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中有效。
答案 1 :(得分:2)
在Oracle中,使用sum() ... over()
窗口函数可以轻松完成运行总和:
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
答案 2 :(得分:1)
查看分组集,可以汇总总数。
不确定这是你所追求的......
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