Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql where子句中的if条件_Sql_Conditional Statements - Fatal编程技术网

Sql where子句中的if条件

Sql where子句中的if条件,sql,conditional-statements,Sql,Conditional Statements,我想从表中检索列,具体取决于条件。, 我能用的 例如,我有几个字段,即添加订单注释、取消订单注释、推迟订单注释、操作(添加、取消、推迟)和收到金额(是/否) 现在,我必须获取列添加订单注释、取消订单注释、推迟订单注释,具体取决于操作和收到的金额 if(action='add' and amount received='Y') then i've to fetch add order comments column elseif(action='postpone' and amount recei

我想从表中检索列,具体取决于条件。, 我能用的

例如,我有几个字段,即添加订单注释、取消订单注释、推迟订单注释、操作(添加、取消、推迟)和收到金额(是/否)

现在,我必须获取列添加订单注释、取消订单注释、推迟订单注释,具体取决于操作和收到的金额

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。如果没有,请使用您的语言中相应的对等词

您需要使用语句()

例如,在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
还要注意,在您给出的规则中,如果
amountcd
字段不是
Y
,则您将得到“Unrecogned action”作为注释。我想你可能需要澄清你的规则来防止这种情况。

试试这个

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'

MySQL、MS SQL Server、Oracle等?