1

I want to retrieve the columns from the table., depending on the conditions., what I can use.

For example, I' ve fields namely, add order comments, cancel order comments, postpone order comments, action(add, cancel, postpone) and amount received(Y/N)

Now I've to fetch columns add order comments, cancel order comments, postpone order comments depending on action and amount received.,

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

how to get this done in sql or plsql., I want this conditions in select statement

4

3 回答 3

3

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

于 2012-11-15T11:55:24.067 回答
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
于 2012-11-15T11:55:57.003 回答
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'
于 2012-11-15T12:03:39.777 回答