优化特定表的查询

时间:2015-03-26 07:33:36

标签: sql-server indexing query-optimization query-performance query-tuning

我有一张桌子,我正在寻找一种方法来改善其性能。下面是一个要执行的查询列表。

dbo.CustomersSmallOrders
(
    ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    CustomerName VARCHAR(MAX) NOT NULL,
    OrderDate DATETIME NOT NULL,
    Quantity INT NOT NULL,
    Amount DECIMAL(15,2) NOT NULL,
    AvailableAmount DECIMAL(15,2) NOT NULL,
    Type TINYINT NOT NULL,
    Status TINYINT NOT NULL
)

请问您能否帮我改写下面的查询并在表格中添加索引以提高其性能?

SELECT *
FROM CustomersSmallOrders
WHERE Left(CustomerName, 4) = 'Levis'

SELECT *
FROM CustomersSmallOrders
WHERE DateDiff(month, OrderDate, GetDate()) >= 30

SELECT *
FROM CustomersSmallOrders
WHERE Quantity * 2 < 3400

SELECT 
    SUM(CASE 
            WHEN Type = 2 AND STATUS IN (0, 1, 2) THEN Amount 
            ELSE 0 
        END)
    ,SUM(CASE 
             WHEN Type = 1 AND STATUS IN (0, 1) THEN Amount 
             ELSE 0 
         END)
    ,SUM(CASE 
             WHEN Type = 2 AND STATUS IN (0, 1) THEN Amount - AvailableAmount 
             ELSE 0 
         END)
FROM CustomersSmallOrders
WHERE STATUS IN (0, 1, 2)

1 个答案:

答案 0 :(得分:2)

查询改进:

正如Martin Smith所说,第一个查询可以转换为

SELECT TOP 0 * FROM CustomersSmallOrders

由于矛盾。

原来是

WHERE Left(CustomerName, 5) = 'Levis'

然后将条件更改为

WHERE CustomerName LIKE 'Levis%'

会保留查询sargable并允许使用索引。

可以通过更改条件并在OrderDate上添加索引来改进第二个查询:

SELECT *
FROM CustomersSmallOrders
WHERE OrderDate <= DATEADD(Mounth, -30, GetDate()) 

第3个(在数量上添加索引):

SELECT *
FROM CustomersSmallOrders
WHERE Quantity < 1700

第4个 - 在STATUS上添加一个索引,其中还包含Type,Amount和AvailableAmount(虽然我不明白为什么他想要Amount两次。我认为这可能是一个错误,他只想要一列输出):< / p>

SELECT 
SUM(CASE 
        WHEN Type = 2 THEN Amount 
        ELSE 0 
    END)
,SUM(CASE 
         WHEN Type = 1 AND STATUS IN (0, 1) THEN Amount 
         ELSE 0 
     END)
,SUM(CASE 
         WHEN Type = 2 AND STATUS IN (0, 1) THEN Amount - AvailableAmount 
         ELSE 0 
     END)
FROM CustomersSmallOrders
WHERE STATUS IN (0, 1, 2)