繁体   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