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

时间:2015-04-14 10:38:12

标签: sql-server subquery scalar-subquery

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

我不是每次都重写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 ....

1 个答案:

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