sql-serversubqueryscalar-subquery

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


I am writing a query, which is using SubQuery to get some result.

Instead of rewriting the SubQuery every time, i want to use the same output value of column 1 as input to another column for the further calculation.

Point 1: Can we use any variable to save the value into it and use the same for another column.

Sample expected code:

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

Solution

  • Well, you can't. There are ways to achieve what you want:

    A.) using subquery

    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.) using the expression itself

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