製品
product_id product_serial_number product_status
1 X123 PENDING
1 X123 PROCESSED
2 X345 PENDING
3 X678 PENDING
4 Y890 PENDING
4 Y890 PROCESSED
上の表は、製品のステータスとその履歴を示しています。出力が次のようになるレポートを作成する必要があります。
product_id status
1 UPDATE
2 NEW
3 NEW
4 UPDATE
つまり、製品が以前に処理された場合 (例: 製品 1 と 4)、そのステータスは UPDATE です。それ以外の場合、そのステータスは NEW です。
私はこのクエリを思いつきましたが、そのパフォーマンスに満足していません:
select product_id, 'UPDATE'
from products p1
where product_id in (select product_id from products p2 where p2.product_status='PROCESSED' and p2.product_status='ARCHIVED')
Union
select product_id, 'NEW'
from products p1
where product_id not in (select product_id from products p2 where p2.product_status='PROCESSED' and p2.product_status='ARCHIVED')
別の方法として、テーブルをそれ自体に結合することもできます。
select p1.product_id, decode(p2.product_id, null, 'NEW','UPDATE')
from products p1, products p2
where p1.product_id=p2.product_id(+)
and p1.product_serial_number=p2.serial_number(+)
and p2.product_status(+) = 'PROCESSED'
いずれかのクエリが大規模なデータ セットに対して実行される場合、パフォーマンスはあまり良くありません。最高のパフォーマンスを得るために、上記のクエリをどのように改善 (または完全に変更) できますか?