sql server中的索引/聚簇索引结构

时间:2012-01-04 21:15:29

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

我正在运行此报告:

use SalesDWH
go
;with
cte_biggie as(
select (c.npi+'|'+ CAST(DATEPART(yy, [DATE entered]) as varchar) +'|'+ 
CASE WHEN DATEPART(mm, [DATE entered]) = 01 THEN 'Jan' 
           WHEN DATEPART(mm, [DATE entered]) = 02 THEN 'Feb'
           WHEN DATEPART(mm, [DATE entered]) = 03 THEN 'Mar'
           WHEN DATEPART(mm, [DATE entered]) = 04 THEN 'Apr'
           WHEN DATEPART(mm, [DATE entered]) = 05 THEN 'May'
           WHEN DATEPART(mm, [DATE entered]) = 06 THEN 'Jun'
           WHEN DATEPART(mm, [DATE entered]) = 07 THEN 'Jul'
           WHEN DATEPART(mm, [DATE entered]) = 08 THEN 'Aug'
           WHEN DATEPART(mm, [DATE entered]) = 09 THEN 'Sep'
           WHEN DATEPART(mm, [DATE entered]) = 10 THEN 'Oct'
           WHEN DATEPART(mm, [DATE entered]) = 11 THEN 'Nov'
           WHEN DATEPART(mm, [DATE entered]) = 12 THEN 'Dec'
           END
           +'|'+isnull(cast(COUNT([specimen id]) as varchar),'') +'|'+isnull([practice name],'')+'|'+isnull(b.[mlis practice id],'')+'|'+a.[practice code]+'|'+[Requesting Physician]+'|'+isnull(c.salesrep,'')+'|'+
    isnull(cast(c.dateestablished as varchar),'')+'|'+ ISNULL (c.practiceaddress1,'')+'|'+ISNULL ( c.practiceaddress2 , '' )+'|'+ISNULL (c.practicecity,'')+'|'+ISNULL (c.practicestate,'')+'|'+
    ISNULL(b.[Active Inactive],'')) [result]
from quicklabdump a
    inner join qlmlismapping b
    on (b.[practice code] = a.[practice code])
    inner join PracticeandPhysician c
    on (a.[Requesting Physician]=c.doctorfirstname+' '+c.DOCTORLASTNAME
        and a.[practice code]=c.practicecode)
where   DATEPART(yy, [DATE entered]) in (2010,2011)
    and DATEPART(mm, [DATE entered]) in (01,02,03,04,05,06,07,08,09,10,11,12)

group by DATEPART(yy, [DATE entered]), DATEPART(mm, [DATE entered]), a.[practice name],b.[mlis practice id],a.[practice code],
    a.[Requesting Physician],c.salesrep,c.dateestablished, c.practicecity,c.practicestate,c.npi,c.practiceaddress1 ,c.practiceaddress2,
    b.[Active Inactive]


)
select 'NPI|Year Entered|Month Entered|Count|Practice Name|MLIS Code|Practice Code|Physician|Sales Rep|Date Established|Address|Address2|City|State|Status'
union all
select * from cte_biggie

因为我正在加入3个表,所以我想知道使用索引和聚簇索引优化此查询的最佳方法是什么。

我会在哪些列上添加索引?

目前此报告需要20秒。数据库大概是5演出。

1 个答案:

答案 0 :(得分:1)

我要做的第一件事是更改WHERE子句 - 目前,它不是sargable,这意味着即使在Date Entered列上有一个索引,也不会使用它,因为你正在使用DATEPART函数它

相反,请执行:

WHERE [Date Entered] >= '20100101' AND [Date Entered] < '20120101'

这是我改变的第一件事,并确保在输入日期时有一个索引。这个可能作为聚簇索引是一个很好的竞争者,尽管在不了解更多数据访问/加载模式等的情况下很难为整个环境选择最佳索引策略。

要检查的其他初始事项是关于连接中涉及的其他表中的字段的索引。