簡體   English   中英

如果條款在where子句中

[英]if conditions in where clause

我想從表中檢索列。取決於條件。我可以使用什么。

例如,我有字段,添加訂單評論,取消訂單評論,推遲訂單評論,操作(添加,取消,推遲)和收到的金額(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語句中使用這個條件

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

您需要使用CASE(T-SQL)語句( PL-SQL等效

例如,在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 ,那么您將獲得“無法識別的操作”作為注釋。 我認為您可能需要澄清您的規則以防止這種情況發生。

嘗試這個

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

如果我已正確理解您的問題,那么實現此目的的另一種方法是執行三個單獨的查詢,然后將它們組合在一起。

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'

暫無
暫無

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

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