从主查询中排除一些行

Exclude some rows from main query

我想从每年每个公司的查询中排除两个最大帐户,我在 pl-SQL 中编写查询但是它很慢我怎样才能重写它以更好地执行?

我的主要 table 包含 9195771 行。

如果有人能帮助我,我将不胜感激

SELECT  
    g."COMPANY", g."ACCOUNTING_YEAR", SUM(g."AMOUNT")
FROM
    accounting_attribute_con a
INNER JOIN
    dana_gl_hold_vou_row_qry_dash g ON a.code_part_value = g."ACCOUNT" 
                                    AND g."COMPANY" = a.company
WHERE
    g."ACCOUNTING_YEAR" IN ('2019', '2018')
    AND g."COMPANY" IN ('DB','DD','DC','DG','DP','DO' )
    AND accounting_attribute_value_api.get_desc(a.company, attribute, ATTRIBUTE_VALUE) = 'others'
    AND g."ACCOUNTING_PERIOD" <> '13'
    AND g."ACCOUNTING_YEAR"||g."COMPANY"||g."ACCOUNT" NOT IN (SELECT FROM (SELECT SUM(g."AMOUNT"), g."ACCOUNTING_YEAR" acc_year, g."COMPANY" company, g."ACCOUNT_DESC", g."ACCOUNT" acc, RANK() OVER (partition by g."ACCOUNTING_YEAR", g."COMPANY"  ORDER BY SUM(g."AMOUNT") DESC) AS rnknumber
                                  FROM accounting_attribute_con a
                                  INNER JOIN dana_gl_hold_vou_row_qry_dash g ON a.code_part_value = g."ACCOUNT" AND g."COMPANY" = a.company
                                  WHERE g."ACCOUNTING_YEAR" IN ('2019', '2018')
                                    AND g."COMPANY" IN ('DB','DD','DE','DG','DP','DO' )
                                    AND accounting_attribute_value_api.get_desc(a.company, attribute, ATTRIBUTE_VALUE) = 'others'
                                    AND g."ACCOUNTING_PERIOD" <> '13'
                                  GROUP BY g."ACCOUNTING_YEAR" , g."COMPANY"  , g."ACCOUNT_DESC" , g."ACCOUNT") b
               WHERE 
                   rnknumber <= 2) 
GROUP BY
    g."COMPANY", g."ACCOUNTING_YEAR"

如果您可以在查询中定义最大帐户数,则可以使用 MINUS 运算符从主查询中排除这些记录。