Removing duplicates of column2 then group them based on column1 , then sum the values of column3 in sql

Viewed 51

The table looks like

column1  column2    column3
400196  2021-07-06   33
400196  2021-07-06   33
400196  2021-08-16   33

I want to get the sum of column3 values based on grouping of column 1 but the duplicate values of date should not be added

The desired output is:

column1  column3
400196   66

The query I wrote is

select sum(column3)
from table_name
group by column1

But this gives me result 99

2 Answers

You can remove duplicate values in a subquery:

select t.column1, sum(t.column3)
from (select distinct t.column1, t.column2, t.column3
      from t
     ) t
group by t.column1;

Note: This sort of problem can arise when you are joining tables together. Removing duplicates may not always be the right solution. Often it is better to do the calculation before joining, so you don't have duplicate values to deal with.

You could use a two step process here, first remove duplicates, then aggregate and sum:

SELECT column1, SUM(column3) AS column3
FROM (SELECT DISTINCT column1, column2, column3 FROM yourTable) t
GROUP BY column1;

enter image description here

Demo

Related