-1

I have my table

My Table

I want to get duplicates from the Name and Status column, count them, and sum values from the Sum column. I want to look like this:

Result

I am new to SQL so that it may be an easy answer, but I can't seem to find a solution.

This is how far I got, but I can't seem to get the count and sum without errors.

SELECT name, COUNT(*) AS recovered 
FROM complaints 
WHERE status = "Recovered" 
GROUP BY name 
HAVING COUNT(name) > 0

myQuery

Rick James
  • 135,179
  • 13
  • 127
  • 222
zhadox
  • 1
  • 3

1 Answers1

2

You can do conditional aggregation:

select 
    name,
    sum(status = 'Recovered') recovered,
    sum(status = 'Unrecovered') unrecovered,
    sum(case when status = 'Recovered' then `sum` end) total_recovered_value,
    sum(case when status = 'Unrecovered' then `sum` end) total_unrecovered_value
from mytable
group by name
order by name

Side note: sum is a language keyword, hence not a good choice for a column name.

GMB
  • 216,147
  • 25
  • 84
  • 135