2012-12-03 77 views
0

道歉模糊的問題標題,但不能確定正確的措辭,請糾正,如果需要的話。mysql返回單行和多行狀態

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

它產生如下的結果:

enter image description here

在結果

,你可以看到,每一個風險有應對風險的兩個訓練方案。我想返回另一列status,看起來每個訓練和訓練完成的字段,如果任一訓練完成,然後狀態good其他狀態bad。所以對於每個風險,我的輸出在這個例子中只有兩行。如果沒有任何培訓已經完成,則顯示任何training價值是需要的。

理想輸出:

enter image description here

如何修改這個查詢來達到預期的效果。

在此先感謝。做

回答

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 FIDDLE EXAMPLE