优化内联查询

时间:2016-05-17 08:36:23

标签: sql db2

是否可以优化以下SQL查询?

SELECT *
FROM (
  SELECT msi.segment1,
         msi.segment2,
         mmt.inventory_item_id,
         count(*) OVER (PARTITION BY msi.segment1,msi.segment2,mmt.inventory_item_id) AS shipped_count
  FROM mtl_material_transactions mmt,
       mtl_system_items msi
  WHERE mmt.inventory_item_id = msi.inventory_item_id
    AND mmt.inventory_item_id IN (SELECT inventory_item_id ROM mtl_system_items WHERE segment2 = '92155')
    AND mmt.transaction_type_id = '63'
    AND trunc(mmt.creation_date) BETWEEN '1-APR-2015' AND '30-APR-2015'
)

1 个答案:

答案 0 :(得分:0)

我怀疑你的主要问题是你的嵌套选择语句。如果将这些分成简单的内部联接,您应该看到更及时的结果......

    select msi.segment1, msi.segment2, mmt.inventory_item_id, count(*) over (partition by msi.segment1, msi.segment2, mmt.inventory_item_id) as SHIPPED_COUNT
    from mtl_material_transactions mmt
    inner join mtl_system_items msi on msi.inventory_item_id = mmt.inventory_item_id
    where msi.segment2 = '92155'
       and mmt.transaction_type_id = '63'
       and year(mmt.creation_date) = 2015 and month(mmt.creation_date) = 4
    group by msi.segment1, msi.segment2, mmt.inventory_item_id

我认为你需要一个GROUP BY子句,因为你已经在你的选择中使用了聚合函数count(*)和列值。

希望这有帮助!