[英]sql sum duplicates in multiple columns
I'm trying to sum values from duplicates rows (with the same ID, Month and Person) in multiple columns to the first or the last duplicate row. 我试图将多个列中重复行(具有相同的ID,Month和Person)的值求和到第一行或最后一个重复行。 Then delete the duplicate rows exept the one with the total value.
然后删除重复的行,除以总值。 The biggest problem is that sometimes I need to sum values in two different columns.
最大的问题是有时我需要对两个不同的列中的值求和。
PrimaryTable: 主表:
ID Month Person Value1 Value2
**123 1 Smith** 10 20
**123 1 Smith** 5 NULL
**123 1 Smith** NULL 5
123 2 Smith 10 5
**189 3 Murphy** NULL 15
**189 3 Murphy** NULL 10
190 2 Brown 25 25
**345 2 Lee** 25 20
**345 2 Lee** 25 20
Result1 (expected result after sum duplicates values to the first one): Result1(求和后的预期结果将值重复到第一个):
ID Month Person Value1 Value2
123 1 Smith **15** **25**
123 1 Smith 5 NULL
123 1 Smith NULL 5
123 2 Smith 10 5
189 3 Murphy NULL **25**
189 3 Murphy NULL 10
190 2 Brown 25 25
345 2 Lee **50** **40**
345 2 Lee 25 20
FinalTable (expected result after deleting duplicates, except the first one): FinalTable(删除重复项后的预期结果,第一个除外):
ID Month Person Value1 Value2
123 1 Smith **15** **25**
123 2 Smith 10 5
189 3 Murphy NULL **25**
190 2 Brown 25 25
345 2 Lee **50** **40**
I'm trying with this code: 我正在尝试使用以下代码:
SELECT ID, Month, Person, SUM(Value1), SumValue2
FROM
(
SELECT ID, Month, Person, Value1, SUM(Value2) AS SumValue2
FROM db.Hours
GROUP BY ID, Month, Person, Value1
)
GROUP BY ID, Month, Person, SumValue2
But sometimes it makes double sum of total of Value2. 但是有时它会使Value2的总数加倍。
SELECT ID, Month, Person, SUM(Value1) as SumValue1, SUM(Value2) AS SumValue2
FROM db.Hours
GROUP BY ID, Month, Person
I am not sure why you are looking at this as two steps etc. There is no removal of duplicates etc. this is a scenario for Group By Aggregation. 我不确定您为什么将其视为两个步骤,等等。没有删除重复项等。这是“按汇总”的方案。 Where you group like rows and summarize the value columns.
在哪里像行一样分组并汇总值列。 The only reason you would need to make this a multi step operation would be if one of your value columns will be considered within your grouping eg ID, Month, Person, and Value1.
您需要执行此多步骤操作的唯一原因是,如果将在您的分组中考虑其中一个值列,例如ID,Month,Person和Value1。 In your case you simply need to group by ID, Month, Person and do the aggregation for Value1 and Value2.
在您的情况下,您只需要按ID,Month,Person分组并为Value1和Value2进行汇总。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.