sql - 使用 COUNT 的多重选择语句

标签 sql oracle aggregate-functions

我正在尝试组合这两个选择查询,但计数函数让我与 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/

相关文章:

sql - Postgresql:如何在 PostgreSQL 中使用 "crosstab"?

MySQL innodb 外键

c# - 在 C# 中将字符串转换为 DateTime 并写入 SQL

java - 如何在jdbc中检索record%type表?

sql - 在选择子查询中,如何从一行中选择一个值,然后从下一行中选择一个值,依此类推?

sql - 基于聚合的更新 - T/SQL

sql - 选择与 usercolumn 不同的值以及 usercolumn 中每个字段的日期最小值

MySql 请求在 LEFT JOIN 上返回重复项

sql - 使字符串在数据库中保持不区分大小写的唯一性

java - Oracle JDK Update 5 (1.7.0_05) 无法在 SUSE Linux Enterprise Server 11 上运行。连接到 Javaspace Blackboard (JINI) 时出现 EOFException