日期:2014-05-16  浏览次数:20374 次

三千万数据汇总查询,求大神效率优化
SELECT
c_store_id + s.c_sname AS 机构 ,
c_adno AS 部门,
c_ccode AS 商品类别,
c_gcode as 商品编码,
t.c_name as 商品名称,
sum(case when DATEDIFF(DAY,t.c_dt,@StartDate_Cur) <= 0 and DATEDIFF(DAY,t.c_dt,@EndDate_Cur) >= 0 then c_number_sale else 0 end) as 当期销售数量,
sum(case when DATEDIFF(DAY,t.c_dt,@StartDate_Cur) <= 0 and DATEDIFF(DAY,t.c_dt,@EndDate_Cur) >= 0 then 0 else c_number_sale end) as 比较期销售数量,
sum(case when DATEDIFF(DAY,t.c_dt,@StartDate_Cur) <= 0 and DATEDIFF(DAY,t.c_dt,@EndDate_Cur) >= 0 then c_sale else 0 end) as 当期销售金额,
sum(case when DATEDIFF(DAY,t.c_dt,@StartDate_Cur) <= 0 and DATEDIFF(DAY,t.c_dt,@EndDate_Cur) >= 0 then 0 else c_sale end) as 比较期销售金额,
sum(case when DATEDIFF(DAY,t.c_dt,@StartDate_Cur) <= 0 and DATEDIFF(DAY,t.c_dt,@EndDate_Cur) >= 0 then c_at_sale else 0 end) as 当期销售成本,
sum(case when DATEDIFF(DAY,t.c_dt,@StartDate_Cur) <= 0 and DATEDIFF(DAY,t.c_dt,@EndDate_Cur) >= 0 then 0 else c_at_sale end) as 比较期销售成本
FROM(
--当期数据
select 
c_store_id,
c_adno,
c_ccode,
c_gcode,
t.c_name,
c_dt,
c_number_sale,
c_sale,
c_at_sale
from tbs_d_gds t(nolock)
where t.c_dt >= @StartDate_Cur
and t.c_dt < @EndDate_Cur
AND EXISTS (select 1 from dbo.uf_split_string(@分类,',') a where t.c_ccode like a.c_str+'%')
AND EXISTS (select 1 from dbo.uf_split_string(@机构代码,',') a  where c_store_id like a.c_str+ '%' )
and (ISNULL(@商品编码,'')='' or exists (select 1 from dbo.uf_split_string(@商品编码,',') a  where t.c_gcode like a.c_str+'%' ))
UNION ALL
--比较期
select 
c_store_id,
c_adno,
c_ccode,
c_gcode,
t.c_name,
c_dt,
c_number_sale,
c_sale,
c_at_sale
from tbs_d_gds t(nolock)
where t.c_dt >= @StartDate_Old
and t.c_dt < @EndDate_Old
AND EXISTS (select 1 from dbo.uf_split_string(@分类,',') a where t.c_ccode like a.c_str+'%')
AND EXISTS (select 1 from dbo.uf_split_string(@机构代码,',') a  where c_store_id like a.c_str+ '%')
and (ISNULL(@商品编码,'')='' or exists (select 1 from dbo.uf_split_string(@商品编码,',') a  where t.c_gcode like a.c_str+'%' ))
)t
LEFT JOIN tb_store s ON t.c_store_id = s.c_id
GROUP BY c_store_id,c_adno,c_ccode,c_gcode,t.c_name,s.c_sname


以上是对数据的查询语句,《tbs_d_gds》表有三千多万的数据,所用到的查询字段,分组字段均有建立索引,并且该表做过表分区处理。。查询数据的时间段为一个月的数据,数据量大概在三百万上下。。先语句执行的时间是17S,想控制在5秒上下。。求大神指导!!!
------解决方案--------------------