2

我正在编写一个查询,它使用 SubQuery 来获得一些结果。

我不想每次都重写子查询,而是想将第 1 列的相同输出值用作另一列的输入以进行进一步计算。

第 1 点:我们可以使用任何变量将值保存到其中并将其用于另一列。

示例预期代码:

  SELECT COLUMN1
        ,CASE WHEN (SELECT CancelDate FROM TABLE3 WHERE EXPR....) <> '' THEN 'Cancel' ELSE 'New' END AS **TransactionType**
        ,COLUMN2
        ,CASE **TransactionType** WHEN 'Cancel' THEN EXPR 1.... 
         CASE **TransactionType** WHEN 'New' THEN EXPR 2 .... END AS CALCOLUMN2     
FROM TABLE1
JOIN TABLE2 ....
4

1 回答 1

2

好吧,你不能。有几种方法可以实现您想要的:

A.) 使用子查询

SELECT Column1, 
       TransactionType,
       CASE TransactionType WHEN 'Cancel' THEN EXPR 1.... 
         CASE TransactionType WHEN 'New' THEN EXPR 2 .... END AS CALCOLUMN2  
FROM
(

   SELECT COLUMN1
        ,CASE WHEN (SELECT CancelDate FROM TABLE3 WHERE EXPR....) <> '' THEN   'Cancel' ELSE 'New' END AS **TransactionType**   
   FROM .....
) ...

B.) 使用表达式本身

SELECT COLUMN1
        ,CASE WHEN (SELECT CancelDate FROM TABLE3 WHERE EXPR....) <> '' THEN 'Cancel' ELSE 'New' END AS TransactionType
        ,COLUMN2
        ,CASE (CASE WHEN (SELECT CancelDate FROM TABLE3 WHERE EXPR....) <> '' THEN 'Cancel' ELSE 'New' END) WHEN 'Cancel' THEN EXPR 1.... 
         CASE (CASE WHEN (SELECT CancelDate FROM TABLE3 WHERE EXPR....) <> '' THEN 'Cancel' ELSE 'New' END) WHEN 'New' THEN EXPR 2 .... END AS CALCOLUMN2     
FROM TABLE1
JOIN TABLE2 ....
于 2015-04-14T10:42:12.340 回答