SQL - 我可以根据另一个新列计算新列吗?

时间:2015-03-04 17:43:01

标签: sql sql-server

我正在创建一个查询,其中有一个新列计算类似于以下内容:

CASE WHEN DATEDIFF(day,lastpurchase,getdate())< 31 AND
turnover >= 3000 THEN '500'
WHEN DATEDIFF(day,lastpurchase,getdate())< 31 AND
turnover < 3000 THEN '200'
ELSE '0' END as OfferAmountEuro,

这很好用。我现在想在同一个表上创建另一个计算字段,在其计算中使用'OfferAmountEuro'字段。我试过这样的事情:

CASE WHEN DATEDIFF(day,lastpurchase,getdate())< 31 AND
turnover >= 3000 THEN '500'
WHEN DATEDIFF(day,lastpurchase,getdate())< 31 AND
turnover < 3000 THEN '200'
ELSE '0' END as OfferAmountEuro,
CASE WHEN OfferAmountEuro = 500 AND Currency ='USD' then '600'
WHEN OfferAmountEuro = 200 AND Currency ='USD' then '250'
ELSE '0' END as OfferAmountLocal

但是我收到一条错误消息,指出'OfferAmountEuro'是一个无效的列名。我认为这意味着我不能在'OfferAmountLocal'的计算中使用新计算的'OfferAmountEuro'字段?

“OfferAmountEuro”字段的实际计算要比现实中的上述内容复杂得多,而且我不想重复“OfferAmountLocal”字段的每个计算。

是否有人建议您在另一个新字段的计算中快速使用此“OfferAmountEuro”字段?

2 个答案:

答案 0 :(得分:1)

由于自然的sql语句执行顺序,您的列无法识别。在这里阅读更多:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/70efeffe-76b9-4b7e-b4a1-ba53f5d21916/order-of-execution-of-sql-queries

如果您使用的是SQL Server,则可以使用CROSS APPLY作为解决方法。

SELECT CASE
        WHEN D.OfferAmountEuro = 500 AND T.Currency ='USD' then '600'
        WHEN D.OfferAmountEuro = 200 AND T.Currency ='USD' then '250'
        ELSE '0'
    END AS OfferAmountLocal
FROM YourTable AS T
CROSS APPLY (
    SELECT CASE
            WHEN DATEDIFF(DAY, T.LastPurchase, GETDATE()) < 31 AND T.TurnOver >= 3000 THEN '500'
            WHEN DATEDIFF(DAY, T.LastPurchase, GETDATE()) < 31 AND T.TurnOver < 3000 THEN '200'
            ELSE '0'
        END
    ) AS D(OfferAmountEuro)

答案 1 :(得分:0)

您可以将原始查询放在WITH语句中,并在第二个查询中引用它,或者将第一个计算列中的所有逻辑替换为您想要使用它的任何位置。

类似的东西:

WITH C1 AS (
    SELECT *, 
        CASE WHEN DATEDIFF(day,lastpurchase,getdate())< 31 AND turnover >= 3000 THEN '500'
        WHEN DATEDIFF(day,lastpurchase,getdate())< 31 AND turnover < 3000 THEN '200'
        ELSE '0' END as OfferAmountEuro
    FROM myTable
    )
SELECT *, 
   CASE WHEN OfferAmountEuro = 500 AND Currency ='USD' then '600'
        WHEN OfferAmountEuro = 200 AND Currency ='USD' then '250'
        ELSE '0' END as OfferAmountLocal
FROM C1