簡體   English   中英

如何在SQL中使用案例陳述

[英]How to use case statment in SQL

我在SQL中遇到這種情況,我需要顯示dr_DRVNUM,DR_DRVNAME和為在同一天工作了相同班次的司機的工作天數。

我在SQL中有此代碼,到目前為止,我也嘗試過其他代碼,但還是沒有運氣

select dr_drvname, dr_drvnum, sh_wkdate
case  when sh_drvnum = dr_drvnum and sh_wkshift = 'DAY' then count(sh_wkdate)
end 
from driver, shift

我有一張桌子,我要在下面上傳部分桌子圖片,

DR_DRVNUM      DR_DRVNAME           SH_WKDATE        SH_WKSHIFT 

0001           Cooper, Randolph B.  15-NOV-07        DAY
0001           Cooper, Randolph B.  15-NOV-07        DAY
0001           Cooper, Randolph B.  15-NOV-07        DAY
0001           Cooper, Randolph B.  15-NOV-07        EVE
0001           Cooper, Randolph B.  15-NOV-07        EVE
0001           Cooper, Randolph B.  15-NOV-07        EVE
0001           Cooper, Randolph B.  15-NOV-07        NIG
0001           Cooper, Randolph B.  15-NOV-07        NIG
0001           Cooper, Randolph B.  15-NOV-07        NIG
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        DAY
0001           Cooper, Randolph B.  16-NOV-07        EVE
0001           Cooper, Randolph B.  16-NOV-07        EVE

了解您要查找的內容有點困難。 與其他字段一起使用count時,應使用group by子句。 這聽起來也像您應該使用count case

select 
    dr_drvname, 
    dr_drvnum,
    sh_wkdate,
    count(case when sh_wkshift = 'DAY' then 1 end)
from driver d
    left join shift s on s.sh_drvnum = d.dr_drvnum
group by
    dr_drvname, 
    dr_drvnum,
    sh_wkdate

BTW-這使用outer join來連接驅動程序和移位表以返回所有驅動程序,即使它們沒有移位。 根據您想要的結果,僅使用inner join可能會很好。

暫無
暫無

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

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