1
\$\begingroup\$

I'm working on an application that counts the number of employees in each department.

Here's my code:

SELECT 
 count(case when (JS_TITLE = 'Accounting')then 1 end)as Accounting,
 count(case when (JS_TITLE = 'Management')then 1 end)as Management,
 count(case when(JS_TITLE = 'Marketing')then 1 end )as Marketing,
 count(case when(JS_TITLE = 'HR')then 1 end)as HR
FROM EMP
LEFT JOIN JOB_STATUS ON EMP.JS_REF = JOB_STATUS.JS_REF

but the thing is, the user may add a new department.

Is there a better way to make this static code more dynamic?

asked Feb 20, 2020 at 7:16
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can use a GROUP BY clause to group by JS_TITLE, then you must transpose the record into a column matrix:

SELECT 
 JS_TITLE, 
 count(EMP.JS_REF)
FROM EMP
LEFT JOIN JOB_STATUS ON EMP.JS_REF = JOB_STATUS.JS_REF
GROUP BY JS_TITLE
Graipher
41.6k7 gold badges70 silver badges134 bronze badges
answered Feb 20, 2020 at 8:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.