iT邦幫忙

0

SQL CASE應用問題

目前語法如下
select tableA.1 , tableA.2
from tableA;
我想使用case 條件如下
select tableA.1 , tableA.2
case tableA.1 /* 當tableA.1符合條件A或B時,帶出不同table的欄位值
when '條件A' then tableB.1
when '條件B' then tableC.1
else 0
end
from tableA;

Dion iT邦新手 5 級 ‧ 2019-05-23 07:47:52 檢舉
好像怪怪的?
說明中是不是少提到 tableA tableB tableC 三者之間的關係
tlcric iT邦新手 5 級 ‧ 2019-05-23 10:02:51 檢舉
其中有某些欄位有關連
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
sion
iT邦新手 4 級 ‧ 2019-05-22 16:02:24
最佳解答

看起來去JOIN其他table就行了吧
你試試看

select case when '條件A' then tableB.1
            when '條件B' then tableC.1
            else 0
       end 
       as result 
from tableA 
join tableB on tableA.1 = tableB.1
join tableC on tableA.1 = tableC.1
tlcric iT邦新手 5 級 ‧ 2019-05-24 16:23:48 檢舉

我試出來了,謝謝
最後是用left join 完成

0
stephen3342
iT邦新手 2 級 ‧ 2019-05-22 17:39:21

將您的 Table A 改為 PERSON
CASE WHEN 裏面可以使用 SubQuery

SELECT PERSON.person_id,
PERSON.name,
(CASE WHEN LEFT(PERSON.person_id,1)='A' THEN
(SELECT SecurityUser.login_id FROM SecurityUser WHERE SecurityUser.person_id=PERSON.person_id)
ELSE
'NO DATA'
END ) AS LoginID
FROM PERSON

我要發表回答

立即登入回答