iT邦幫忙

0

關於SQL When...then...語法問題

  • 分享至 

  • twitterImage

各位好,小弟有個問題如下:

select
case
when TABLE.currency_id='USD' then '1'
when TABLE.currency_id='RMB' then 'A'
end "匯率",

其中的**'A'** 必須從TABLE的某一欄位取出,
因為該欄位每天都在更新,所以沒辦法寫死。

小弟試過直接在then後面接select,去select那個欄位,
但是回報錯誤,仔細看過語法規格後,好像不能做這樣的動作。

請問各位前輩,我該如何解決?

新手上路,問題問得不好,請多多賜教。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
7
kissingboy
iT邦新手 4 級 ‧ 2012-12-12 10:31:27
最佳解答

如果要從同一個資料表中的其他欄位[A]取人民幣匯率,直接填寫該欄位

<pre class="c" name="code">
select
case
when TABLE.currency_id='USD' then '1'
when TABLE.currency_id='RMB' then [TABLE].[A]
end "匯率"
FROM TABLE

如果要從不同資料表[TABLE_B]的某欄位[A]取人民幣匯率,then後面的select語法要取成唯一值

<pre class="c" name="code">
select
case
when TABLE.currency_id='USD' then '1'
when TABLE.currency_id='RMB' then (SELECT TOP 1 A FROM [TABLE_B])
end "匯率"
FROM TABLE

是否要用 END AS '匯率' 還是 END "匯率" 剛剛測試似乎是都可以

4
純真的人
iT邦大師 1 級 ‧ 2012-12-11 16:50:27

不知道你的想要做什麼的查詢~

你的寫法是錯的~

case when else end只能在同資料表內查詢~

最好提供資料表例子參考,你目前的資料是什麼..

正確用法應該是以下方式:
select
(case when currency_id = 'USD' then '1' else 'A' end) as 匯率
from table1

4
wiseguy
iT邦超人 1 級 ‧ 2012-12-11 21:46:25

這樣會不會比較快:

<pre class="c" name="code">
select 1 as 匯率 from TABLE where currency_id='USD'
union
select A欄位 as 匯率 from TABLE where currency_id='RMB'
4
summertw
iT邦好手 1 級 ‧ 2012-12-12 09:24:58

select
case
when TABLE.currency_id='USD' then '1'
when TABLE.currency_id='RMB' then 'A'
end "匯率",
...

你說的錯誤訊息,問題應該是出在,【"匯率"】這裡...
你的程式應該是以美元為基底的匯率算用程式,所以這個'A'應該是人民幣的浮動匯率。
請試試看寫成如下...
select
case
when TABLE.currency_id='USD' then '1'
when TABLE.currency_id='RMB' then [TABLE].[ColumnA]
end AS 匯率 ,
...

我要發表回答

立即登入回答