Sql 使用COUNT的多个Select语句

Sql 使用COUNT的多个Select语句,sql,oracle,aggregate-functions,Sql,Oracle,Aggregate Functions,我试图结合这两个select查询,但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) GRO

我试图结合这两个select查询,但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

做这件事的最佳(有效)方法是什么?

这里有两种方法。我很确定SUM案例会更好,但你可以自己测试

使用和的情况

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;
使用连接

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

我相信你想依靠事件的身份而不是个人身份;这样,您就可以将两个查询合并为一个查询,并得到您想要的结果。

太好了!如何从结果中排除两列值均为0的行?@madlan在(1,2)中为第一列的where子句添加了
和incident.incident\u id。我想第二个已经这样做了join似乎为同一个人返回了多个结果(行)?很抱歉,您需要添加一个
DISTINCT