简体   繁体   中英

Select only 20 rows of every distinct name

I have a table in which I have over 1000+ rows, in which there is a column "AnaId", values of this column are repeated many times like name 003912 is repeated 85 times, name 003156 in repeated 70 time, I want to select maximum 20 rows of every distinct AnaID. I have no idea how to do it.

SELECT dbo.Analysis.AnaId, Analysis.CasNo, MoleculeId,

    SUM(dbo.AnalysisSummary.Area) as TotalArea

    FROM dbo.Analysis LEFT JOIN dbo.AnalysisSummary

    ON dbo.AnalysisSummary.AnaId = dbo.Analysis.AnaId

    WHERE dbo.Analysis.Sample like '%Oil%'

    GROUP BY dbo.Analysis.AnaId,Analysis.CasNo, MoleculeId ORDER BY 

    TotalArea DESC

You can use row_number() :

select t.*
from (select t.*, row_number() over (partition by name order by name) as seqnum
      from t
     ) t
where seqnum <= 20;

With the edits to your question, you can do:

with t as (
      <your query here without order by>
     )
    select t.*
    from (select t.*, row_number() over (partition by name order by name) as seqnum
          from t
         ) t
    where seqnum <= 20;

If you have another table of names, you can also use cross apply :

select t.*
from names n cross apply
     (select top 20 t.*
      from t
      where t.name = n.name
     ) t;

Using Rank()

select t.*
from (select t.*, rank() over (partition by name order by name) as seqnum
      from t
     ) t
where seqnum <= 20;

Using Dense_Rank()

select t.*
from (select t.*, Dense_Rank() over (partition by name order by name) as seqnum
      from t
     ) t
where seqnum <= 20;

Using Row_Number

   select t.*
    from (select t.*, row_number() over (partition by name order by name) as seqnum
          from t
         ) t
    where seqnum <= 20;

This will help uunderstand usage of each Special Functions

Base Code Credits:-@gordon

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