DinhNgocHien
DinhNgocHien

Reputation: 717

Select if else in MySQL

I encountered a problem to select and change name of columns based on specific condition. For example, if I have a table A which has name, date, value attributes where:

name    |date         |value
iphone  |2015-05-01   |1
ipad    |2015-05-09   |3
ipod    |2015-05-20   |6

Now I want to select this table satisfy condition that if name is not equal samsung, nokia so it should assign to apple and value should be sum if they are in the same month. For example, this table will show the result:

name    |date        |value
apple   |2015-05     |10 

Can someone help me?

Upvotes: 0

Views: 35

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Here's the idea : you can use aliases in the group by clause in mysql, but if the alias is equal to a column name, I guess you'll have some problems.

select 
       case when name in ('samsung', 'nokia') then name else 'apple' end as name1,
       EXTRACT( YEAR_MONTH FROM date)  as date1,
       SUM(value) as value
from table1
group by 
  name1,
  date1

see SqlFiddle

Upvotes: 1

Related Questions