简体   繁体   English

mysql返回单行和多行状态

[英]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. 我有以下MySQL查询,它将我的几个表连接在一起。

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 . 我想返回到每个训练和训练完成字段的另一列status ,如果任何一个训练完成,则状态为good否则为状态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. 如果没有完成任何training ,则根据需要显示任何training价值。

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 SQL范例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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