我正在尝试将这两个选择查询结合起来,但是count函数让我对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
我正在尝试将单个结果返回为:
FIRST_NAME ACTIVE NonActive
Bob 5 11
John 3 14
这样做的最佳(有效)方法是什么?
答案 0 :(得分:3)
以下是两种方法。我很确定SUM CASE会更好但你可以自己测试
使用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;
使用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
答案 1 :(得分:0)
我相信你想要对incident_id而不是person_id进行计数;这样,您可以将两个查询合并为一个并获得所需的结果。