I have a table and I am only interested in two columns to perform two actions (Ignore or Good), and based on actions I need to keep only "Good" rows. I have tried several SQL windows functions but not able to achieve what I am looking for.
Here is the data:
There are two actions I need to perform on each row. "cat" or "dog" will be "Good" only when there is value "animal" in the column before on the same date otherwise action will be "Ignore". Similar to this:
Final result should be like this:
2
Answers
Looks like you can just use a conditional windowed
COUNT
.Then simply put that into a subquery and filter on it.
One option could be to self join your table data like in the subquery below and use LAG() Over() analytic function as a Case expression’s condition to get the "Good" rows.
Self inner join will eliminate the rows with val = ‘animal’ with no cat or dog or whatever on the same date. Case expression checks if the previous row with the same date has val = ‘animal’ or not. Outer query is filtered using Where clause and grouped by to get ridd of duplicates.
See the fiddle here.