0

I have two select statements with union and I wanna show the result in multiple columns or side by side.

I try this:

SELECT COUNT(emp.id) num1,dep.departmentname
from tblemployees emp
JOIN tbldepartments dep on dep.id = emp.OriginalDepartment
WHERE
emp.OriginalDepartment IN (208,168,209,189,157)
and emp.JobType in (41,51,52,53,54) 
AND emp.`Status`NOT IN (11,20,21,26,17) 
AND emp.retiredate > CURDATE()
GROUP BY dep.departmentname
union
SELECT COUNT(emp.id) num2,dep.departmentname
from tblemployees emp
JOIN tbldepartments dep on dep.id = emp.OriginalDepartment
WHERE
emp.OriginalDepartment IN (208,168,209,189,157)
and emp.JobType IN (1,6,7,8,9,11,26,32,33,34,36,43,45,46,47,48,49,55) 
AND emp.`Status`NOT IN (11,20,21,26,17) 
AND emp.retiredate > CURDATE()
GROUP BY dep.departmentname
the result show like this:
num1 departmentname
4 dep 2
5 dep 3
20 dep 4
50 dep 5
53 dep 2
56 dep 3
30 dep 4
16 dep 5
19 dep 6
40 dep 7

and I wanna to show the results like this:

num1 num2 departmentname
4 53 dep 2
5 56 dep 3
20 30 dep 4
50 16 dep 5
19 dep 6
40 dep 7
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

1 Answers1

-1

Conditionally aggregate instead

for example:-

DROP TABLE IF EXISTS T;

CREATE TABLE T
(dept VARCHAR(20),   type int);
INSERT INTO T VALUES
('one', 41),
('one', 41),
('one', 41),
('one', 41),
('two', 52),

('one', 1),
('one', 6),
('one', 1),
('two', 1),
('three', 6);

select dept, 
         sum(case when type in (41,52) then 1 else 0 end) num1,
         sum(case when type in (1,6) then 1 else 0 end) num2
from t
group by dept;

+-------+------+------+
| dept  | num1 | num2 |
+-------+------+------+
| one   |    4 |    3 |
| three |    0 |    1 |
| two   |    1 |    1 |
+-------+------+------+
3 rows in set (0.002 sec)

need more help search for mysql pivot , still struggling publish REPRESENTATIVE sample data and desired outcome as text.

P.Salmon
  • 17,104
  • 2
  • 12
  • 19