Search code examples
sqlgroup-bysumaggregate-functions

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


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


Solution

  • 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