简体   繁体   中英

mysql return single row and status for multiple rows

apologies for vague question title but not sure on correct wording, please correct if need be.

I have the following MySQL query which joins several of my tables together.

select distinct(o.person), 
    o.job,
    p.risk,
    r.training,
    case when c.datecompleted  is null then 'no' else 'yes' end TrainingCompleted,
    case when c.expirydate is null then '' else c.expirydate end expirydate
from 
    orgstructure o 
    join personrisks p on p.Person=o.person
    right outer join risktraining r on r.risk=p.risk
    left outer join coursescompleted c on c.course=r.training and c.person=o.person
where o.department='house keeping' and o.person <> ''
order by o.person desc

it produces the below result:

在此处输入图片说明

in the result, you can see that each risk has two training solutions that address the risk. I want to return another column status that looks to each training and training completed field, if either of the training is completed then status good else status bad . so my output will only have two rows in this example for each risk. should none of the training have been completed then show any training value as being needed.

ideal output:

在此处输入图片说明

How do I edit this query to achieve the desired results.

Thanks in advance.

easiest way to do it is

select 
    o.person,
    o.job,
    p.risk,
    case when count(c.datecompleted) > 0 then null else r.training end as training,
    case when count(c.datecompleted) > 0 then 'yes' else 'no' end as TrainingCompleted,
    case when count(c.datecompleted) > 0 then 'good' else 'bad' end as Status
from orgstructure o 
    join personrisks p on p.Person=o.person
    right outer join risktraining r on r.risk=p.risk
    left outer join coursescompleted c on c.course=r.training and c.person=o.person
where o.department='house keeping' and o.person <> ''
group by o.person
order by o.person desc, case when c.datecompleted is not null then 0 else 1 end asc

Here I do not showing training if either of traning is completed.

SQL FIDDLE EXAMPLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM