如果条款在where子句中

时间:2012-11-15 11:51:31

标签: sql conditional-statements

我想从表中检索列。取决于条件。, 我能用什么。

例如,我有字段,即添加订单评论,取消订单评论,推迟订单评论,操作(添加,取消,推迟)和收到的金额(是/否)

现在我要获取列添加订单评论,取消订单评论,推迟订单评论,具体取决于收到的操作和金额。

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语句中使用这个条件

3 个答案:

答案 0 :(得分: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,那么您将获得“无法识别的操作”作为评论。我认为您可能需要澄清您的规则以防止这种情况发生。

答案 1 :(得分: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

答案 2 :(得分: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'