看板 Database 關於我們 聯絡資訊
※ 引述《ylk (YLK)》之銘言: : id used time : --------- ------- -------- : A 5 13:30 : B 5 13:00 : C 4 14:00 : D 1 12:00 : E 0 11:00 : 各位前輩好,想請教一下一個SQL問題。 : 需求:找到 time 時間最早的資料,不過,如果 used 有 > 0 的,要優先選擇。 : 以上列資料表來看,我要選擇的是 資料D。 : 想了很久,還是想不出來這個 SQL 要怎麼下,請問有人能幫忙提醒一下嗎? : 謝謝! 只取一筆 select * from T order by case when (used > 0) then 1 else 0 end desc, time asc limit 1 噁心的寫法 select * from T join ( select case when used > 0 then 1 else 0 end as u, min(time)as t from T group by case when used > 0 then 1 else 0 end) x on x.u = case when used > 0 then 1 else 0 end and x.t = T.time where (exists(select * from T where used > 0) and used > 0) or (not exists(select * from T where used > 0) and used = 0) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.104.29.35