我试图根据两列对数据进行求和,其中2行中的值相等。这是我的桌子:
Country | System | Money
AAA | A | 10
AAA | A | 200
AAA | B | 60
BBB | B | 600
BBB | A | 150
BBB | B | 140这就是我想要达到的目标:
Country | System | Money | SystemSum
AAA | A | 10 | 210
AAA | A | 200 | 210
AAA | B | 60 | 60
BBB | B | 600 | 740
BBB | A | 150 | 150
BBB | B | 140 | 740这就是我尝试过的:
SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)但是它会累计地返回值。怎样才能做好呢?
发布于 2020-02-18 14:48:37
可以执行窗口和,但需要删除rows子句:由于指定了rows unbounded preceding,查询只考虑前面的行,而希望对整个分区进行求和:
select
t.*,
sum(money) over(partition by country, system) systemsum
from mytable as t附带注意:指定没有order的preceding行实际上是没有意义的--使用此语法,将在分区中考虑一组未定义的行。
发布于 2020-02-18 14:47:31
你可以做一个小组
select a.Country, a.System, a.Money, SystemSum
from tbl a inner join
(
select Country, System,
SUM(Money) as SystemSum
from tbl
group by Country, System
) b on a.Country = b.Country and a.System = b.System与前面没有界的行一起使用的窗口函数将累加所有货币的前面的值,从而得到以前的结果。
发布于 2020-02-18 14:50:38
您似乎想要Country和System组合的总和。使用窗口函数是可行的,但使用的是partition by而不是order by
SELECT t.*,
SUM(Money) OVER (PARTITION BY Country, System)
FROM t;https://stackoverflow.com/questions/60283476
复制相似问题