简体   繁体   中英

oracle in clause along with rownum

I am not an oracle expert so I am hoping someone could help me with this question..

I have a scenario where I need to query the top 1000 records from a table and my query already has a IN clause for the where section. For example, lets say there is a table called employee which has 4 columns,

  • name
  • salary
  • state
  • country

and I want to query for first 1000 records where state is in(MA or NY or NH), how do i do that?

select name, salary
from Employee
where state IN ('MA','NY','NH')

Now the problem is that if I use rownum < 1000 at the end, it is going to just find all results and show only the top 1000. But what I want to see if top 1000 of each State value in the IN Clause... Can someone please suggest the right way to do this...

Thanks in advance...

You want to use row_number() :

select e.name, e.salary
from (select e.*, row_number() over (partition by state order by state) as seqnum
      from employee e
      where state in ('MA', 'NY', 'NH')
     ) e
where seqnum <= 1000;

I'm not sure what you mean by the "top 1000 of each state". You have no order by or suggestion of ordering in your question. And, SQL tables are inherently unordered. This returns 1000 values for each state from indeterminate rows.

Use this:

Select name, salary
from Employee
where state IN ('MA','NY','NH')
Group by state
HAVING Count(*) <=1000
Order by state

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM