So here's the situation- our records use a compound key of name/date. I want to see all names that have performed 2 specific actions in a row, so I want to do something like
select name from
(select name as n, date as d from table where action='action1'),
(select name from table where name = n and date > d and action='action2' and rownum=1 order by date desc)
but it counts n and d as invalid identifiers. How can I get it to do what I need?
One method might be:
SELECT
a1.name
FROM
(SELECT name, date FROM table WHERE action = 'action1') a1
JOIN
(SELECT name, date FROM table WHERE action = 'action2') a2
ON
a2.name = a1.name
AND
a2.date > a1.date
If there can be more than one instance of each action for a single name, this might give you duplicates. In this case, it might be sufficient to use SELECT DISTINCT
to eliminate the dups.
Note that this doesn't mean that the two actions happened immediately one after the other, just that action2 happened sometime after action1.
Analytical functions are perfect for this sort of thing.... disclaimer this is quick and dirty and the column names are a little misleading. LAG/LEAD are the options you want to play with
http://sqlfiddle.com/#!4/bd7b2/7
select name,thedate,theaction,prev_action,prev_date from
(
select name,thedate,theaction,
lag(theaction) over (partition by name order by thedate,theaction) as prev_action,
lag(thedate) over (partition by name order by thedate,theaction) as prev_date
from table1
order by name,thedate,theaction
)
where theaction = 'action1' and prev_action = 'action2'
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.