从连接表中分组和计数

时间:2016-06-29 02:29:44

标签: mysql sql

我试图为每个学习者排一行,格式如下:

<div id="left">
        <ul id="menu">
            <li><img src="http://www.w3schools.com/bootstrap/img_chania.jpg"/></li>
            <li><img src="http://www.w3schools.com/bootstrap/img_chania2.jpg"/></li>
            <li><img src="http://www.w3schools.com/bootstrap/img_flower2.jpg"/></li>
            <li><img src="http://www.w3schools.com/bootstrap/img_flower.jpg"/></li>
            <li><img src="http://www.w3schools.com/bootstrap/img_flower2.jpg"/></li>

        </ul>
    </div>
    <img id ="right" src="http://www.w3schools.com/bootstrap/img_chania.jpg"/>

学习者有很多提供者,提供者有很多学习者 在每个提供者,学习者有很多结果,结果属于一个学习者 结果有一个标准,一个标准属于无/多个结果
标准有很多职业

nsn|last_name|first_name|middle_name|gender|ethnicities|providers|qualifications|vocation_PI|vocation_SI|.....

我无法得到每个职业的计数。

我在每个计数字段中得到相同的值(不确定这是否是所有计数的总数或者是什么)

预期产出:

select l.nsn, l.last_name,l.first_name,l.middle_name, l.gender, GROUP_CONCAT(distinct e.name SEPARATOR '|') as ethnicities, GROUP_CONCAT(distinct p.name SEPARATOR '|') as providers, count(case v.code when 'PI' then 1 else 0 end) as v_PI,count(case v.code when 'SI' then 1 else 0 end) as v_SI,count(case v.code when 'CR' then 1 else 0 end) as v_CR, GROUP_CONCAT(distinct q.name SEPARATOR '|') as qualifications
from learners l 
join learner_ethnicity le on l.id = le.learner_id
join ethnicities e on le.ethnicity_id = e.id
join learner_provider lp on l.id = lp.learner_id
join providers p on lp.provider_id = p.id
join results r on lp.id = r.learner_provider_id
join standards s on r.standard_id = s.id
join standard_vocation sv on s.id = sv.standard_id
join vocations v on sv.vocation_id = v.id
join learner_qualification lq on l.id = lq.learner_id
join qualifications q on lq.qualification_id = q.id
group by l.id

实际输出:

123451234 | Doe | John | James | M | European|Maori | SecondaryProvider|TertiaryProvider | NCEA Level 1|NCEA Level 2|Farming PHD | 185 | 430 | .....

有什么建议吗?

感谢。

1 个答案:

答案 0 :(得分:2)

用SUM替换你的计数你会得到你想要的东西

select l.nsn, l.last_name,l.first_name,l.middle_name, l.gender, GROUP_CONCAT(distinct e.name SEPARATOR '|') as ethnicities, GROUP_CONCAT(distinct p.name SEPARATOR '|') as providers, sum(case v.code when 'PI' then 1 else 0 end) as v_PI, sum(case v.code when 'SI' then 1 else 0 end) as v_SI,sum(case v.code when 'CR' then 1 else 0 end) as v_CR, GROUP_CONCAT(distinct q.name SEPARATOR '|') as qualifications
from learners l 
join learner_ethnicity le on l.id = le.learner_id
join ethnicities e on le.ethnicity_id = e.id
join learner_provider lp on l.id = lp.learner_id
join providers p on lp.provider_id = p.id
join results r on lp.id = r.learner_provider_id
join standards s on r.standard_id = s.id
join standard_vocation sv on s.id = sv.standard_id
join vocations v on sv.vocation_id = v.id
join learner_qualification lq on l.id = lq.learner_id
join qualifications q on lq.qualification_id = q.id
group by l.id