我试图基于两列求和,其中两行中的值相等。 这是我的桌子:
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)
,但它会累积返回值。如何正确执行?
答案 0 :(得分:3)
您可以进行窗口求和,但是您需要删除rows
子句:由于您指定了rows unbounded preceding
,因此查询只考虑了前面的行,而您希望对整个分区求和:
select
t.*,
sum(money) over(partition by country, system) systemsum
from mytable as t
旁注:不按顺序指定preceding
行实际上是没有意义的-使用这种语法,您会在分区内得到一组 undefined 行。
答案 1 :(得分:1)
您可以分组
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
与ROWS UNBOUNDED PRECEDING一起使用的窗口函数将累计所有Money的先前值,因此您之前获得的结果
答案 2 :(得分:1)
您似乎想要Country
和System
的组合之和。可以使用窗口函数,但是使用partition by
而不是order by
:
SELECT t.*,
SUM(Money) OVER (PARTITION BY Country, System)
FROM t;
答案 3 :(得分:1)
您似乎只是按(country, system)
分组。试试看:
SELECT
Country, System, Money,
SUM(Money) OVER(PARTITION BY Country, System) AS SystemSum
FROM MyTable
这将为您提供基于组的SUM
,而且还返回所有详细的行数据。
答案 4 :(得分:0)
您可以根据需要使用over partition by子句。
WITH TBL(COUNTRY,SYSTEM,MONEY) AS (
SELECT 'AAA' AS COUNTRY,'A' AS SYSTEM ,10 AS MONEY FROM DUAL UNION ALL
SELECT 'AAA' AS COUNTRY,'A' AS SYSTEM ,200 AS MONEY FROM DUAL UNION ALL
SELECT 'AAA' AS COUNTRY,'B' AS SYSTEM ,60 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'B' AS SYSTEM ,600 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'A' AS SYSTEM ,150 AS MONEY FROM DUAL UNION ALL
SELECT 'BBB' AS COUNTRY,'B' AS SYSTEM ,140 AS MONEY FROM DUAL )
SELECT COUNTRY,SYSTEM,MONEY,SUM(MONEY)OVER(PARTITION BY COUNTRY,SYSTEM) AS SUMALL FROM TBL