[英]SQL Sum Up Values by Group
I have a following table person_amounts.我有一个下表person_amounts。
Person_id Item_Amount
1 50
1 10
1 10
1 20
2 30
2 40
2 40
I want to write a query so that a new column Total is the sum of items by person.我想编写一个查询,以便新列 Total 是每个人的项目总和。 So the result would be:所以结果将是:
Person_id Item_Amount Total
1 50 90
1 10 90
1 10 90
1 20 90
2 30 110
2 40 110
2 40 110
I could write something like:我可以这样写:
select person_id, item_amount, (select sum(item_amount) from person_amounts pa
where pa.person_id = p.person_id) Total from person_amounts p
However, the problem is that this query will sum up all the rows in my table for each person id.但是,问题是此查询将汇总表中每个人 ID 的所有行。 This will cause a problem if I add a where condition to limit the data.如果我添加 where 条件来限制数据,这将导致问题。 I am looking to have the Total column populate the sum based on the rows that are in my result.我希望 Total 列根据我的结果中的行填充总和。 So if I add a where condition like所以如果我添加一个 where 条件,比如
where item_amount >= 20
I'd like the results to show the following:我希望结果显示以下内容:
Person_id Item_Amount Total
1 50 70
1 20 70
2 30 110
2 40 110
2 40 110
You simply want a window function:你只需要一个窗口函数:
select person_id, item_amount,
sum(item_amount) over (partition by person_id)
from person_amounts pa
where item_amount >= 20;
Window functions are standard SQL supported by basically all databases.窗口函数是基本所有数据库都支持的标准SQL。
If you want to use a subquery -- which is less performant and more verbose -- then you need to filter the results in the subquery as well as in the outer query.如果您想使用子查询——它的性能较低且更冗长——那么您需要过滤子查询以及外部查询中的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.