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

时间:2015-09-12 10:35:43

标签: sql sql-server calculated-columns

我有以下查询:

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)两次,我相信这是表现不佳的选择。

如何以优雅的方式完成此任务(避免重复计算)?

1 个答案:

答案 0 :(得分:1)

添加计算列:

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];