如何将计算列值用于同一 SQL 查询中的另一列

How to use calculated column value to another column in the same SQL Query

我正在编写一个查询,它使用 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 ....

嗯,你不能。有很多方法可以实现你想要的:

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 ....