基于另一个计数 - MySQL

时间:2018-05-12 12:56:36

标签: mysql join count

我有以下Set of tables,我希望获得所有服务,年龄范围和性别,并且每三个旁边都有与之对应的收件人数。 到目前为止,我想出了下面的陈述,它确实有效。

select s.service_name,s.service_id,g.gender_id,ag.age_range_id,count(r.recipient_id) Temp
from tbl_services s inner join tbl_gender g
                    inner join tbl_age_range ag
                    left join tbl_recipient_services rs on rs.service_id=s.service_id
                    left join tbl_recipient r on r.gender_id=g.gender_id and rs.recipient_id=r.recipient_id 
                                              and (year(sysdate())-year(r.recipient_birth_date) >=  min_age and year(sysdate())-year(r.recipient_birth_date) <=  max_age)
group by s.service_id,g.gander_id,ag.age_range_id

但我只需要计算tbl_recipient_services中有2项或更多服务的收件人,并且我再次陷入困境。

任何人都有想法解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

首先,使用cross join s:

可以更清楚地查询
select s.service_name, s.service_id, g.gender_id, ag.age_range_id,
       count(r.recipient_id) as all_recipients
from tbl_services s cross join
     tbl_gender g cross join
     tbl_age_range ag left join
     tbl_recipient_services rs
     on rs.service_id = s.service_id left join
     tbl_recipient r
     on r.gender_id = g.gender_id and
        rs.recipient_id = r.recipient_id and
        year(sysdate()) - year(r.recipient_birth_date) >=  min_age and
        year(sysdate()) - year(r.recipient_birth_date) <=  max_age)
group by s.service_id, g.gender_id, ag.age_range_id;

即使没有匹配项,也会返回服务/性别/年龄的所有组合。

让我们添加另一列。为此,我们将使用子查询来计算每个收件人的服务数量,然后将其包括在计数中:

select s.service_name, s.service_id, g.gender_id, ag.age_range_id,
       count(r.recipient_id) as num_recipients,
       sum(rs2.num_services >= 2) as num_recipients_2plus 
from tbl_services s cross join
     tbl_gender g cross join
     tbl_age_range ag left join
     tbl_recipient_services rs
     on rs.service_id = s.service_id left join
     tbl_recipient r
     on r.gender_id = g.gender_id and
        rs.recipient_id = r.recipient_id and
        year(sysdate()) - year(r.recipient_birth_date) >=  min_age and
        year(sysdate()) - year(r.recipient_birth_date) <=  max_age) left join
    (select rs2.recipient_id, count(*) as num_services
     from tbl_recipient_services rs2
     group by rs2.recipient_id
    ) rs2
    on rs2.recipient_id = r.recipient_id
group by s.service_id, g.gender_id, ag.age_range_id;

如果您不想要其他列,可以将left join更改为内部联接并删除count(r.recipient_id)