how can I rewrite the query in more effecient way say using the with clause:
SELECT DISTINCT
work_number,
FIRST_VALUE (comments)
OVER (PARTITION BY work_number ORDER BY comments_date DESC)
AS comments,
FIRST_VALUE (comments_date)
OVER (PARTITION BY work_number ORDER BY comments_date DESC)
AS comments_date,
FIRST_VALUE (comments_source)
OVER (PARTITION BY work_number ORDER BY comments_date DESC)
AS comments_source,
FIRST_VALUE (comment_type)
OVER (PARTITION BY work_number ORDER BY comments_date DESC)
AS comments_type
FROM (SELECT c.work_number,
CASE
WHEN c.comments IS NULL THEN 'no comment entered'
ELSE c.comments
END
AS comments,
c.comments_date,
'n/a' comments_source,
'General' comment_type
FROM myschema.ledg_work_comment c
UNION
SELECT ls.work_number,
CASE
WHEN s.comments IS NULL THEN 'no comment entered'
ELSE s.comments
END
AS comments,
ls.status_date comments_date,
'n/a' comments_source,
'Status' comment_type
FROM myschema.v_ledg_work_last_status ls, myschema.ledg_work_status s
WHERE ls.work_status_id = s.work_status_id
UNION
SELECT r.work_number,
CASE
WHEN r.comments IS NULL THEN 'no comment entered'
ELSE r.comments
END
AS comments,
r.receipt_adj_date comments_date,
'n/a' comments_source,
CASE
WHEN r.receipt_adj_type = 'R' THEN 'Receipt'
ELSE 'Adjustment'
END
AS comment_type
FROM myschema.ledg_work_receipt r);
by: paquicubaPosted on 2009-09-29 at 14:09:56ID: 25453496
WITH Clause? You use the WITH clause when a subquery returns a value or a resultset that can be reused in different parts of the main query.
In your case, you need to avoid SORTing.
1. Try to replace UNION with UNION ALL
2. Try to avoid Analytic functions (Window sorts) with large resultsets.