利用交叉申请重用计算列

leveraging cross apply for reusing calculated column

我有一个 productTable,我正在阅读专栏,进行计算并在以后重复使用相同的计算。

INSERT INTO #tempTable
(
    productName,
    quantity,
    priceInUSD,
    isValidPrice,
    discountDescription
)
SELECT  TOP (1000) WITH TIES
        pt.productName,
        pt.quantity,
        pt.priceInUSD,
        IIF(pt.priceInUSD >= 10000 OR pt.priceInUSD < 0 , 0, 1) AS isValidPrice,
        IIF(isValidPrice > 0, '10% discount allowed', 'Max 0 discount allowed' )
FROM    ProductTable pt
WHERE   pt.type like 'stock product'
ORDER BY pt.purchaseId ASC

有没有一种方法可以根据 productTable 的列计算 isValidPrice 并在以后使用 isValidPrice?

    IIF(pt.priceInUSD >= 10000 OR pt.priceInUSD < 0, 0, 1) AS isValidPrice,
    IIF(isValidPrice > 0, '10% discount allowed', 'Max 0 discount allowed' )

您可以将表达式移动到 FROM 子句:

SELECT  TOP (1000) WITH TIES
        pt.productName,
        pt.quantity,
        pt.priceInUSD,
        v.isValidPrice,
        (CASE WHEN v.isValidPrice > 0 THEN '10% discount allowed' ELSE 'Max 0 discount allowed' END)
FROM ProductTable pt CROSS APPLY
     (VALUES (CASE WHEN pr.priceInUSD >= 10000 OR pr.priceInUSD < 0 THEN 0 ELSE 1 END)
     ) v(isValidPrice)
WHERE  pt.type like 'stock product'
ORDER BY pt.purchaseId ASC;

注意:我建议使用 standard SQL 语法而不是定制功能,因此我将 IIF() 更改为 CASE 表达式。