簡體   English   中英

Mysql 查詢空字段替換為自定義 if 語句

[英]Mysql query null field replace with custom if statement

我有以下 Mysql 查詢還沒有按預期工作。 我不是 Mysql 專家,但基本上我想要做的是對於每個 AptStatus = 3 我有一個用於 Operatory 的 Null 字段。 我想將該 Null 字段轉換為每個位置計數的運營商名稱。 (希望這是有道理的)。

select Location, AptDate, IF(AptStatus = 3, '08:00:00', AptTime) AptTime, IF(AptStatus = 3, 540, AptLength) AptLength,AptStatus, OperatoryNum, Operatory
from rpt_officeschedules
where AptTime between '07:59:00' and '17:30:00' and AptDate between '2020-11-07' and '2020-11-08' and (Operatory LIKE '%NP%' or Operatory LIKE '%OPEN%'or Operatory is null )
order by Location, AptDate, OperatoryNum,AptTime, Operatory;

樣本數據

樣本數據

該位置具有來自同一個表的這些運算符。

在此處輸入圖片說明

預期的結果是這樣的

在此處輸入圖片說明

有任何想法嗎?

你似乎想要join

select 
    o.location, 
    o.aptdate, 
    case when o.aptstatus = 3 then '08:00:00' else o.apttime   end as apttime, 
    case when o.aptstatus = 3 then 540        else o.aptlength end as aptlength,
    o.aptstatus, 
    o.operatory, 
    a.operatory as operatorynum
from rpt_officeschedules o
inner join apptwidget_operatorie a on a.location = o.location
where 
    o.apttime between '07:59:00' and '17:30:00' 
    and o.aptdate between '2020-11-07' and '2020-11-08' 
    and (o.operatory like '%np%' or o.operatory like '%open%' or o.operatory is null)
order by o.location, o.aptdate, o.operatorynum, o.apttime, o.operatory;

我認為您可能想要循環遍歷第二個表,以循環方式分配值。 如果是這樣,您可以使用窗口函數:

select os.Location, os.AptDate, 
       (case when os.AptStatus = 3 then '08:00:00' else os.AptTime end) as AptTime,
       (case when os.AptStatus = 3 then 540 else os.AptLength end) as AptLength,
       os.AptStatus, os.OperatoryNum, os.Operatory
from (select os.*,
             row_number() over (partition by location order by atpdate) as seqnum
      from rpt_officeschedules os
      where os.AptTime between '07:59:00' and '17:30:00' and
            os.AptDate between '2020-11-07' and '2020-11-08' and
            (Operatory LIKE '%NP%' or Operatory LIKE '%OPEN%'or Operatory is null )
     ) os join
     (select aw.*, count(*) over (partition by location) as cnt,
             row_number() over (partition by location order by location) as seqnum
      from appwidget ap
     ) ap
     on os.location = ap.location and
        (os.seqnum - 1) % sp.cnt = ap.seqnum - 1
order by os.Location, os.AptDate, os.OperatoryNum, os.AptTime, os.Operatory;

暫無
暫無

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

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