簡體   English   中英

mysql返回單行和多行狀態

[英]mysql return single row and status for multiple rows

對於模糊的問題標題,我們深表歉意,但不確定正確的措詞,請根據需要進行更正。

我有以下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 ,則根據需要顯示任何training價值。

理想輸出:

在此處輸入圖片說明

如何編輯此查詢以實現所需的結果。

提前致謝。

最簡單的方法是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM