2012-11-15 166 views
1

我想從表中檢索列,根據條件。, 我可以使用。如果條件在哪裏條款

例如,我已經領域,即爲了添加註釋,取消訂單的意見,推遲訂單註釋,操作(添加,取消,推遲)和收到的金額(Y/N)

現在我來取列添加秩序的意見,取消訂單的意見,推遲訂單註釋根據行動和收到的款項,

if(action='add' and amount received='Y') 
then 
i've to fetch add order comments column 
elseif(action='postpone' and amount received='Y') 
then 
i've to fetch postpone order comments column 
else (action='cancel') 
then i've to fetch cancel order comments 

如何得到這個SQL或PLSQL做,我想這個條件在SELECT語句

+2

MySQL,MS SQL-Server,Oracle等? – MatBailie

回答

3

請注意,通過「sql或plsql」我假設「sql」是指MS SQL Server使用的T-SQL。如果沒有,請使用您的語言的相應等效語言。

您需要使用CASE (T-SQL)聲明(PL-SQL equivalent

例如,在T-SQL:

SELECT OrderId AS OrderId 
     CASE 
      WHEN Action = 'add' AND amountRcd = 'Y' THEN addOrderComment 
      WHEN Action = 'postpont' AND amountRcd = 'Y' THEN postponeOrderComment 
      WHEN Action = 'cancel' THEN cancelOrderComment 
      ELSE 'Unrecognised action' 
     END AS Comment 
FROM tblOrders 

還要注意的是,在你給的規則,如果amountRcd字段不是Y,那麼你會得到「無法識別的行動」作爲評論。我想你可能需要澄清你的規則,以防止這種情況。

0

試試這個

select order comment case when action ='add' 
    and amount received ='y' 
    else select postpone order comments when action ='postpone' 
    and amount received='y' 
    else select cancel when action ='cancel' end 
    from table 
0

如果我理解正確的問題,那麼實現這一點的另一種方式是執行三個獨立的查詢,然後聯合在一起。

select orderID as OrderID, addOrderComments as Comment 
from tblOrders 
where Action = 'add' AND amountRcd = 'Y' 
union 
select orderID as OrderID, postponeOrderComment as Comment 
from tblOrders 
where Action = 'postpone' AND amountRcd = 'Y' 
union 
select orderID as OrderID, cancelOrderComment as Comment 
from tblOrders 
where Action = 'cancel'