我正在尝试组合这两个选择查询,但计数函数让我与 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
执行此操作的最佳(有效)方法是什么?
最佳答案
这里有两种方法可以做到这一点。我很确定 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
关于sql - 使用 COUNT 的多重选择语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4101356/