计算值SQL表中出现的次数

时间:2016-04-27 11:09:07

标签: sql

情况如下:

因此,在我的数据库中,一个人对作业X“负责”并“链接”到作业Y.我想要的是一个返回的查询:人名,他的ID以及他链接/负责的工作数量。到目前为止我得到了这个:

select id_job, count(id_job) number_jobs
from 
(
select responsible.id
from responsible
union all
select linked.id
from linked
GROUP BY id
) id_job
GROUP BY id_job

它返回第一列中包含id的表和第二列中出现的次数。现在,我不能做的是将人的名字与表格联系起来。当我从头开始把它放在“选择”中时,它给了我所有可能的组合......我怎么能解决这个问题?提前谢谢!

示例数据和理想输出:

| Person |

id | name
1  | John
2  | Francis
3  | Chuck
4  | Anthony

| Responsible  |

process_no | id
100        | 2
200        | 2
300        | 1
400        | 4

| Linked  |

process_no | id
101        | 4
201        | 1
301        | 1
401        | 2

OUTPUT:

| OUTPUT |

id | name    | number_jobs
1  | John    | 3
2  | Francis | 3
3  | Chuck   | 0
4  | Anthony | 2

3 个答案:

答案 0 :(得分:0)

select id, name, count(process_no) FROM (
    select pr.id, pr.name, res.process_no from Person pr
        LEFT JOIN Responsible res on pr.id = res.id
UNION
    select pr.id, pr.name, lin.process_no from Person pr
        LEFT JOIN Linked lin on pr.id = lin.id) src
group by id, name
order by id

查询未经过测试,请试一试,但这是您想要的方式

答案 1 :(得分:0)

我建议由人聚集每个表,然后将结果加回person表:

select p.*, coalesce(r.cnt, 0) + coalesce(l.cnt, 0) as numjobs
from person p left join
     (select id, count(*) as cnt
      from responsible
      group by id
     ) r
     on r.id = p.id left join
     (select id, count(*) as cnt
      from linked
      group by id
     ) l
     on l.id = p.id;

答案 2 :(得分:0)

试试这种方式

select prs.id, prs.name, count(*) from Person prs
join(select process_no, id
     from  Responsible res 
     Union all
     select process_no, id
     from  Linked  lin ) a on a.id=prs.id
group by prs.id, prs.name