对于每个记录表,从另一个记录表中获取最新值,如何更快地运行

时间:2015-01-24 15:06:04

标签: sql-server tsql

我有这个SQL:

        SELECT stage.s_f4101.country, stage.s_f4101.itm, stage.s_f4101.litm, 
stage.s_f4101.aitm, stage.s_f4101.descr, stage.s_f4101.descr_en, 
stage.s_f4101.glpt, stage.s_f4101.barcode, stage.s_f4101.lnty, 
stage.s_f4101.stkt, stage.s_f4101.uom1, stage.s_f4101.uom2, stage.s_f4101.ptsc, 
stage.s_f4101.prp1, stage.s_f4101.prp2, stage.s_f4101.prp3, stage.s_f4101.prp4, 
stage.s_f4101.prp5, stage.s_f4101.prp6, stage.s_f4101.prp7, stage.s_f4101.prp8, 
stage.s_f4101.prp9, stage.s_f4101.prp0, stage.s_f4101.isblk, 
stage.s_f4101.design_id,
      (SELECT top 1 wa
       FROM stage.s_f74g4105 dd
       WHERE dd.mslitm = stage.s_f4101.litm
         AND dd.country=stage.s_f4101.country
       ORDER BY msfyr DESC, mscmon DESC) wa_latest
    FROM stage.s_f4101
    LEFT OUTER JOIN stage.s_udc_41p4 ON stage.s_f4101.country = stage.s_udc_41p4.country
    AND stage.s_f4101.prp4 = stage.s_udc_41p4.udckey
    LEFT OUTER JOIN stage.s_udc_4103 ON stage.s_f4101.country = stage.s_udc_4103.country
    AND stage.s_f4101.prp8 = stage.s_udc_4103.udckey
    LEFT OUTER JOIN stage.s_udc_41p5 ON stage.s_f4101.country = stage.s_udc_41p5.country
    AND stage.s_f4101.prp5 = stage.s_udc_41p5.udckey
    LEFT OUTER JOIN stage.s_udc_4107 ON stage.s_f4101.country = stage.s_udc_4107.country
    AND stage.s_f4101.srp7 = stage.s_udc_4107.udckey
    LEFT OUTER JOIN stage.s_udc_4105 ON stage.s_f4101.country = stage.s_udc_4105.country
    AND stage.s_f4101.prp0 = stage.s_udc_4105.udckey
    LEFT OUTER JOIN stage.s_udc_41p1 ON stage.s_f4101.country = stage.s_udc_41p1.country
    AND stage.s_f4101.prp1 = stage.s_udc_41p1.udckey
    LEFT OUTER JOIN stage.s_udc_41s5 ON stage.s_f4101.country = stage.s_udc_41s5.country
    AND stage.s_f4101.srp5 = stage.s_udc_41s5.udckey

基本上我的问题是它因为得到字段WA_LATEST的子查询而变慢。

我能做些什么来加快速度?

我添加了顾问在S_F74G4105上建议的相对索引

指数:

CREATE NONCLUSTERED INDEX [_dta_index_S_F74G4105_19_1733307122__K6_K1_K7_K8_12] ON [stage].[S_F74G4105]
(
    [MSLITM] ASC,
    [Country] ASC,
    [MSFYR] ASC,
    [MSCMON] ASC
)

2 个答案:

答案 0 :(得分:0)

尝试使用带有row_number()的子查询来检索所有"最新的"一气呵成:

select   s_f4101.country
... 
,        latest.wa
FROM     s_f4101   
...
LEFT OUTER JOIN 
        (
        select  row_number() over (
                    partition by country, mslitm 
                    order by msfyr desc, mscmon desc) as rn
        ,       country
        ,       mslitm
        ,       wa
        from    s_f74g4105
        ) latest
ON      latest.rn = 1 -- Top row ordered by msfyr desc, mscmon desc
        and latest.country = s_f4101.country
        and latest.mslitm = s_f4101.litm
...

答案 1 :(得分:0)

每次获取wa_latest时,您似乎都在为s_f74g4105.wa执行键查找。如果在索引中添加wa作为包含列,它会有帮助吗?看统计数据io&查询计划可能有所帮助,但不要被计划中的百分比所迷惑,这只是估计。