Question

Oracle version: Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod

My table structure:

Field 1: Name
Field 2: Year
Field 2: Sales_Rev
Field 3: Rep_Cat

There are three types of Rep_Cat: Inside, Outside, Lead

I need to identify whenever a Rep_Cat field value changes. So , if in 1993 (year), Bob (name) was an Inside rep (Rep_Cat), and 1994 Bob became an Outside rep, I would want the query to return the 1993 and 1994 Bob rows.

I saw some "With" clauses on this site that purported to do this but after several attempts, I could not get them to work.

Was it helpful?

Solution

This is a very good opportunity for analytic functions. Try this:

select t.*
from (select t.*,
             lag(rep_cat) over (partition by name order by year) as prev_rep_cat
      from t
     ) t
where rep_cat <> pre_rep_cat

Note: This also tells you what the previous value is i the prev_rep_cat field. Also, because NULL automatically fails the comparison, you will not get the first row for each name. (If you wanted that, then include or prev_rep_cat is null in the where clause.)

OTHER TIPS

Assumes Name is a unique Key

This is one possible way..

SELECT * from yourTable where Name in (
SELECT Name
FROM yourtable
GROUP BU name
HAVING count(Distinct Rep_cat) > 1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top