选择查询和聚合函数

时间:2017-02-01 06:04:32

标签: performance sql-server-2012 sql-server-express

我正在使用SQL Server Express版本,我有一个表,每分钟插入500~600行。

表架构是这样的

ColumnName   DataType
CID          varchar(6)
PID          varchar(6)
DID          varchar(6)
MID          byte  
Date_Time    DateTime 
Col1         Decimal(19,6)     
Col2         Decimal(19,6)  
Col3         Decimal(19,6)        
.
.
Col32        Decimal(19,6) 

请注意,只有新行的插入没有更新,并且在任何时间点都不会删除现有行。该表保持了巨大的增长速度(因为我使用的是SQL Server Express版本,因此它会一直增长,直到数据库大小达到10 GB)。

同时我们使用select语句和任何列上的一些聚合函数来获取表,即Col1,Col2 .. Col32,其过滤基于CID,PID,DID,MID,Date_time。

目前,合并的非聚集索引设置为

 (CID, PID, DID, MID, Date_Time)

假设我经常获取Col1,如果我在索引中包含相同的内容,我就会达到提升的性能。但我相信如果我在索引中包含所有32列(Col1, Col2.. Col32),那将不是好方法。

我的查询模式如下所示startdate和enddate之间的差异可能超过3个月,所以我认为服务器必须考虑返回以下查询的结果集的大量数据

Select top(1) 
from table 
where Date_time between <startdate> and <endate> 
  and CID = ‘@cid 
  and PID = ‘@pid’ 
  and DID = ‘@did’ 
  and MID = ‘@mdi’

Select top(1) Col1, Col2 
from table 
where Date_time between <startdate> and <endate> 
  and CID = ‘@cid 
  and PID = ‘@pid’ 
  and DID = ‘@did’ 
  and MID = ‘@mdi’ 
order by Date_Time desc

Select top(1) Col1, Col2 
from table 
where Date_time between <startdate> and <endate> 
  and CID = ‘@cid 
  and PID = ‘@pid’ 
  and DID = ‘@did’ 
  and MID = ‘@mdi’ 
order by Date_Time asc

Select Col1, Col2, Col3, Col4, Col5 
from table 
where Date_time between <startdate> and <endate> 
  and CID = ‘@cid 
  and PID = ‘@pid’ 
  and DID = ‘@did’ 
  and MID = ‘@mdi’ 
order by Date_Time desc

Select Min(Col1), Max(Col2), Avg(Col3) 
 from table 
 where Date_time between <startdate> and <endate> 
   and CID = ‘@cid 
   and PID = ‘@pid’ 
   and DID = ‘@did’  
   and MID = ‘@mdi’ 

现在,我有一项任务是提高此类查询模式的性能,并期望在最多2到3秒内得到结果集。

我可以在表中进行任何修改,只要不进行插入操作就可以添加任何索引。

任何人都可以向我建议我应该做些什么。

1 个答案:

答案 0 :(得分:0)

由于您经常按<audio data-key="32"> <source src="https://dl.dropboxusercontent.com/content_link/bHRDoVQqFTHeLSx1YSynP8x5KaNfBIWyWzPG4zOvb9gBEyGBwNKImdcgmVZutije/file?dl=0&duc_id=dropbox_duc_id" type="audio/mpeg">Audio element not supported. </audio>排序(而不是在Date_Time子句中使用Date_Time),因此我会从您的WHERE中删除Date_Time索引并在Date_Time上创建一个单独的索引。

此外,由于您似乎经常通过Col1检索Col5,因此在主索引中包含这些列可能是个好主意。

所以我试试这个:

CREATE INDEX MainIndex
ON dbo.YourTable (CID, PID, DID, MID)
INCLUDE (Col1, Col2, Col3, Col4, Col5)

CREATE INDEX DateIndex
ON dbo.YourTable (Date_Time)

所以:

  • 第一,衡量您当前的表现
  • 然后进行更改
  • 再次测量性能并查看是否有任何改进 - 如果是,请保留新索引,如果没有,请返回原始设置