I have following table in mysql
emp_id month salary
1 Jan 2000
1 Feb 2000
1 March 2000
2 Jan 3000
2 Feb 3000
2 March 3000
I am trying to get a result like following:
emp_id Jan_sal feb_sal Mar_sal
1 2000 2000 2000
2 3000 3000 3000
My query:
select emp_id,
(case when month = 'Jan' then salary else NUll end ) jan_sal,
(case when month = 'Feb' then salary else NUll end ) feb_sal,
(case when month = 'March' then salary else NUll end ) march_sal
from emp group by emp_id;
But the output I get as:
emp_id jan_sal feb_sal march_sal
1 2000 NULL NULL
2 3000 NULL NULL
Not sure if my query is right. Any help is appreciated.
You want to use an aggregate function like SUM
or MAX
on the case statements
select emp_id,
sum(case when month = 'Jan' then salary else NUll end ) jan_sal,
sum(case when month = 'Feb' then salary else NUll end ) feb_sal,
sum(case when month = 'March' then salary else NUll end ) march_sal
from emp
group by emp_id;
If multiple salaries are present (may be other benefits etc) for same employee, then you have to decide if you want to add all the salaries or take only the max value and use SUM or MAX based on that.
Use the MAX()
function to pivot:
SELECT emp_id,
MAX(CASE WHEN month = 'Jan' THEN salary END) AS jan_sal,
MAX(CASE WHEN month = 'Feb' THEN salary END) AS feb_sal,
MAX(CASE WHEN month = 'March' THEN salary END) AS march_sal
FROM emp
GROUP BY emp_id;
This assumes that each employee only has one salary entry per month. If there could be more than one entry, then use should use your original CASE
expressions with SUM()
instead of MAX()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.