我有以下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
,该列查看每个培训和培训已完成的字段,如果其中一个培训已完成,则状态为good
,状态为bad
。所以我的输出在这个例子中只有两行用于每个风险。如果没有完成任何培训,则显示需要的任何training
值。
理想输出:
如何编辑此查询以获得所需结果。
提前致谢。
答案 0 :(得分: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
如果任何训练完成,我不会在训练中显示训练。