0

为模糊的问题标题道歉,但不确定正确的措辞,如果需要,请更正。

我有以下 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

它产生以下结果:

在此处输入图像描述

结果,您可以看到每个风险都有两个解决风险的培训解决方案。我想返回另一个status查看每个培训和培训完成字段的列,如果其中一个培训已完成,则 status goodelse status bad。所以我的输出在这个例子中对于每个风险只有两行。如果没有完成任何培训,则显示任何training需要的价值。

理想输出:

在此处输入图像描述

如何编辑此查询以获得所需的结果。

提前致谢。

4

1 回答 1

0

最简单的方法是

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

如果任一培训完成,这里我不会显示培训。

SQL 提琴示例

于 2012-12-03T09:46:44.120 回答