uiTeam324
uiTeam324

Reputation: 1245

Sum of value using condition in mysql

I have a table like this. Now i want two sum(hour).. 1 for place_type '1' and another for place_type '2'. Is it possible in mysql?

Now my query is

SELECT sum(hour) as totalHour from category_data group by category_data.user_id

also tried with IF condition but not working

SELECT IF(place_type='1',sum(hour),0) home, 
  IF(place_type='2', sum(hour), 0) center,
    from category_data group by category_data.user_id

user_id   place_type  hour     
  1          1         2
  1          2         5
  2          1         3
  2          2         4
  3          1         2

Thanks in advance

Upvotes: 0

Views: 45

Answers (1)

pala_
pala_

Reputation: 9010

Conditional aggregation is what you need here.

select sum(case when place_type = 1 then `hour` end), 
       sum(case when place_type = 2 then `hour` end)
  from category_data

Example fiddle

Upvotes: 3

Related Questions