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