当前位置: 代码迷 >> Sql Server >> 请教一条sql语句的优化
  详细解决方案

请教一条sql语句的优化

热度:19   发布时间:2016-04-27 12:04:34.0
请问一条sql语句的优化
语句如下
请高人 帮忙优化下

SQL code
declare @c_id  intSEt @c_id =19select  top 10000 *  into #temp from [CarVehicleData_tbl] where [email protected]_id order by [CSN_UpdateTime] descselect max([CSN_ID]) as [CSN_ID],  c_id, [CSN_Part],[CSN_Type], max([CSN_UpdateTime]) as [CSN_UpdateTime] into #temp2from #tempgroup by c_id ,[CSN_Part],[CSN_Type]select *,(select top 1 [CSN_DataOriginal]  from [CarVehicleData_tbl] a where b.csn_updateTime=a.csn_updateTime order by csn_updateTime desc ) as [CSN_DataOriginal] into  #temp3 from #temp2  bselect c_id,[CSN_Part],data1 =max( case csn_type when 0 then [CSN_DataOriginal] end ),data2=max( case csn_type when 1 then [CSN_DataOriginal] end ) into #temp4 from #temp3group by c_id,[CSN_Part]select *,null as a ,null as b from #temp3drop table  #tempdrop table  #temp2drop table  #temp3drop table  #temp4


------解决方案--------------------
除了減少臨時表,沒啥可優化.
------解决方案--------------------
SQL code
declare @c_id  intSEt @c_id =19select  top 10000 *  into #temp from [CarVehicleData_tbl] where [email protected]_id order by [CSN_UpdateTime] DESCCREATE INDEX IX_#temp_ALL ON #temp(c_id,[CSN_Part],csn_type,csn_updateTime,CSN_DataOriginal) INCLUDE ([CSN_DataOriginal])select    a.c_id,     a.[CSN_Part],     data1=MAX(CASE WHEN a.[CSN_Type]=0 THEN b.csn_updateTime IS NOT NULL THEN a.CSN_DataOriginal end),    data2=MAX(CASE WHEN a.[CSN_Type]=1 THEN b.csn_updateTime IS NOT NULL THEN a.CSN_DataOriginal end
  相关解决方案