如何避免 SQL 查询中的计算列重复计算

How to avoid computed-column duplicate computation in an SQL Query

我有以下查询:

Use Northwind 

select OrderID as 'Order ID', (UnitPrice * Quantity) as 'Total', case
when (UnitPrice * Quantity) > 100 then 'Good' else 'Bad'
end as 'Rating' from [Order Details]

理论上,它计算 (UnitPrice * Quantity) 两次,我认为这对性能来说是一个糟糕的选择。

如何优雅地完成这个(避免重复计算)?

添加计算列:

CREATE TABLE [Order Details]
     (..., UnitPrice INT, Quantity INT, Total AS UnitPrice * Quantity PERSISTED);


SELECT 
    OrderID AS 'Order ID',
    Total,
    CASE
       WHEN Total > 100 THEN 'Good'
       ELSE 'Bad'
    END AS 'Rating'
FROM [Order Details];