需要协助来重写此查询

时间:2019-04-26 12:20:48

标签: sql hive query-optimization hiveql

我们在每天运行的生产中有此查询 它进行了大量的连接,并且在配置单元中使用了窗口功能

我们尝试添加一些设置选项,但这并没有太大帮助

结构是这样的-

SELECT
        C.f1, C.f2, A.f2 ...
FROM (
    SELECT * FROM (
        SELECT T1.*, B.atid, B.a_id,
        ROW_NUMBER() OVER (PARTITION BY T1.wtid, B.atid ORDER BY T1.b_ts DESC) AS RANK_
        FROM T1 AS T1
        JOIN T5 ON T1.t_dt = T5.t_dt
        JOIN T2 B ON T1.wtid = B.wtid and T1.b_ts = B.b_ts
        LEFT OUTER JOIN (SELECT p_cd FROM T3 WHERE PV_TY_CD = 'ORIG_CD') PV
        ON T1.TYP = PV.p_cd
        WHERE T1.state not in ("INVALID")
        AND T1.evt_name NOT IN ('INACTIVE','DORMANT')
        AND ISNULL(PV.p_cd)
    ) T
    WHERE T.rank_ = 1
) A

JOIN (SELECT *, row_number() over (partition by ac_id order by b_ts desc) rank_  
      FROM T4
      WHERE event not in ('CT','UPD')
     ) AS C
  ON A.a_id = C.a_id
AND A.atid = C.ac_id
AND C.rank_ = 1
JOIN T6 ON C.t_dt = T6.t_dt
  • 由于我无法忽略任何表(和联接),因此我的方法是使用聚合函数max将窗口函数替换为另一个联接,但我无法重写它。
  • 我也不知道这是否一定会有助于提高性能,因此任何指导都将对我们有所帮助。

1 个答案:

答案 0 :(得分:2)

解析函数通常比带select max的联接执行得更好,因为在解析函数和row_number计算由partition by并行化的情况下,您只读取同一张表。

尝试重新组合联接和过滤。

加入

LEFT OUTER JOIN (SELECT p_cd FROM T3 WHERE PV_TY_CD = 'ORIG_CD') PV
        ON T1.TYP = PV.p_cd

,其中条件ISNULL(PV.p_cd)会减少T1中的某些行。 这些条件相同:

WHERE T1.state not in ("INVALID")
        AND T1.evt_name NOT IN ('INACTIVE','DORMANT')

将此联接移动到子查询中,如果它过滤了lo,这可能有助于在所有其他联接和row_number()之前减少T1中的数据集:

(select T1.* from T1 
             left join (SELECT p_cd FROM T3 WHERE PV_TY_CD = 'ORIG_CD') PV 
                       ON T1.TYP = PV.p_cd 
 where T1.state not in ("INVALID")
        AND T1.evt_name NOT IN ('INACTIVE','DORMANT')
        AND ISNULL(PV.p_cd)
) as T1 

也仅在T1和B表上计算第一个row_number:

PARTITION BY T1.wtid, B.atid ORDER BY T1.b_ts DESC

请考虑在row_number过滤器之后加入T5表,如果此连接很重,并且row_number过滤器正在减少数据集,则将row_number用过滤器再次包装在子查询中,并使用T5过滤联接的子查询。

(--filtered by row_number
select * from
(
 SELECT T1.*, B.atid, B.a_id,
        ROW_NUMBER() OVER (PARTITION BY T1.wtid, B.atid ORDER BY T1.b_ts DESC) AS RANK_
  from
    (select T1.* from T1 
                 left join (SELECT p_cd FROM T3 WHERE PV_TY_CD = 'ORIG_CD') PV 
                           ON T1.TYP = PV.p_cd 
     where T1.state not in ("INVALID")
            AND T1.evt_name NOT IN ('INACTIVE','DORMANT')
            AND ISNULL(PV.p_cd)
    ) as T1 JOIN T2 B ON T1.wtid = B.wtid and T1.b_ts = B.b_ts
) T WHERE T.rank_ = 1
) T --filtered
JOIN T5 ON T1.t_dt = T5.t_d  

这可能会有所帮助,具体取决于您的数据。

另请参阅:https://stackoverflow.com/a/51061613/2700344和此:https://stackoverflow.com/a/51061613/2700344