每个不同的名称只选择20行

时间:2017-07-12 11:44:13

标签: sql sql-server greatest-n-per-group

我有一张表,其中我有超过1000行,其中有一列“AnaId”,此列的值重复多次,如名称003912重复85次,重复70次名称003156,I想要选择每个不同AnaID的最多20行。我不知道该怎么做。

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

2 个答案:

答案 0 :(得分:3)

您可以使用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 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;

如果您有另一个名单表,也可以使用cross apply

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

答案 1 :(得分:0)

使用Rank()

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

使用Dense_Rank()

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

使用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

基本代码积分: - @ gordon