If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Hybrid View

query matching mode

I want to write a query to get the IDs based on codes. For example, I want to get the IDs if they have code 201 and 202. I can do it with the UNION function and id 1 and 2 will be returned.
But how can I find the IDs who has only codes: 201 and 202? That is, I want to get id 2 not 1 and 2.

select id
from ( select id, code,
lag(code,1) over (partition by id order by code) prev_code1,
lead(code,1) over (partition by id order by code) next_code1,
lead(code,2) over (partition by id order by code) next_code2
from your_table)
where prev_code1 is null
and next_code2 is null
and next_code1 = 202
and code = 201