2

I'm trying to combine these two select queries but the count function is confusing me with Oracle:

select person.first_name, COUNT(person.PERSON_ID) as Active
FROM incident, person
where person.PERSON_ID = incident.OWNER_ID
and incident.incident_id = 1
AND (incident.dept_id = 111 OR incident.dept_id = 222)
GROUP BY person.first_name;


select person.first_name, COUNT(person.PERSON_ID) as NonActive
FROM incident, person
where person.PERSON_ID = incident.OWNER_ID
AND incident.incident_id = 2
AND (incident.dept_id = 111OR incident.dept_id = 222)
GROUP BY person.first_name

I'm trying to return a single result as:

FIRST_NAME ACTIVE NonActive
Bob          5       11
John         3       14

What would be the best (efficient) way of doing this?

2 Answers 2

3

Here are two ways to do it. I pretty sure SUM CASE will be better but you can test it yourself

Using SUM CASE

select person.first_name, 
SUM(case when incident.incident_id =1 THEN 1 ELSE 0 END) as Active,
SUM(case when incident.incident_id =2 THEN 1 ELSE 0 END) AS NonActive,

FROM incident, person
where person.PERSON_ID = incident.OWNER_ID

   AND (incident.dept_id = 111 OR incident.dept_id = 222)
   AND incident.incident_id IN (1,2)

GROUP BY person.first_name;

Using JOIN

SELECT  DISTINCT
    p.First_name,
    Acive.Active,
    NonActive.NonActive
FROM
PERSON p

LEFT JOIN 
(
select person.first_name, COUNT(person.PERSON_ID) as Active
FROM incident, person
where person.PERSON_ID = incident.OWNER_ID
and incident.incident_id = 1
AND (incident.dept_id = 111 OR incident.dept_id = 222)
GROUP BY person.first_name;
) Active
ON p.first_name = active.first_name
LEFT JOIN 
(
select person.first_name, COUNT(person.PERSON_ID) as NonActive
FROM incident, person
where person.PERSON_ID = incident.OWNER_ID
AND incident.incident_id = 2
AND (incident.dept_id = 111OR incident.dept_id = 222)
GROUP BY person.first_name
) NonActive

ON p.first_name = NonActive.first_name

where Active.First_name is not null
and NonActive.First_name is not null
Sign up to request clarification or add additional context in comments.

4 Comments

Great! How do I exlude rows that have 0 values for both columns from the results?
@madlan Added AND incident.incident_id IN (1,2) to the where clause for the first one. I think the second one already does this
The join seems to return multiple results (rows) for the same people?
Sorry You'll need to add a DISTINCT
0

I believe you want to do your count on the incident_id instead of person_id; that way, you can combine your two queries into one and get the result you want.

Comments

Your Answer

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.