查询耗费了大量时间......如何解决?

时间:2016-07-22 18:40:50

标签: sql sql-server sql-server-2008

我的SQL Server数据库中有一个表,其中有6列,如下所示

CREATE TABLE Table1
(
    VersionID int NOT NULL,
    EventNum int NOT NULL,
    LossLevelID int NOT NULL,
    PerspCode char(2) NOT NULL,
    Loss float NOT NULL
)

这里前4列是复合主键。

我还没有任何索引。

以下查询将永远存在。如何提高绩效?

SELECT TOP 100 
    T1.EventNum, 
    SUM(CASE WHEN T1.PERSPCODE = 'GR' THEN LOSS END) Gross  
FROM 
    ART.[LA].[Table1] T1 WITH (NOLOCK)  
WHERE 
    EXISTS (SELECT EventNum
            FROM Axis_Accumulation.dbo.AIREventSet
            WHERE RegionPerilId = 27)  
    AND EventNum IN (110000002, 110000003, 110000016, 110000019, 110000034, 110000066, 110000086, 110000116, 110000118, 110000136)
GROUP BY 
    T1.EventNum 
HAVING 
    SUM(CASE WHEN T1.PERSPCODE = 'GR' THEN LOSS END) > + CAST(0 AS VARCHAR(10)) 
ORDER BY 
    EventNum DESC 

1 个答案:

答案 0 :(得分:1)

评论太长了。 EXISTS表达没有意义。通常,这是相关的。所以,我猜你打算:

EXISTS (SELECT 1
        FROM Axis_Accumulation.dbo.AIREventSet aes
        WHERE aes.RegionPerilId = 27 and aes.EventNum = t1.EventNum
       )

其次,HAVING至少可以说是尴尬。为什么要将数字SUM()与字符进行比较?代替:

HAVING SUM(CASE WHEN T1.PERSPCODE = 'GR' THEN LOSS END) > 0

+是非操作。由于比较,表达式无论如何都会转换回数字。

然后我要去的第一个索引(假设上面的EXISTS是正确的)是:AIREventSet(EventNum, RegionPerilId)