Select top 10 records for each category

前端 未结 14 1151
别那么骄傲
别那么骄傲 2020-11-22 04:27

I want to return top 10 records from each section in one query. Can anyone help with how to do it? Section is one of the columns in the table.

Database is SQL Serve

14条回答
  •  感情败类
    2020-11-22 05:21

    If you want to produce output grouped by section, displaying only the top n records from each section something like this:

    SECTION     SUBSECTION
    
    deer        American Elk/Wapiti
    deer        Chinese Water Deer
    dog         Cocker Spaniel
    dog         German Shephard
    horse       Appaloosa
    horse       Morgan
    

    ...then the following should work pretty generically with all SQL databases. If you want the top 10, just change the 2 to a 10 toward the end of the query.

    select
        x1.section
        , x1.subsection
    from example x1
    where
        (
        select count(*)
        from example x2
        where x2.section = x1.section
        and x2.subsection <= x1.subsection
        ) <= 2
    order by section, subsection;
    

    To set up:

    create table example ( id int, section varchar(25), subsection varchar(25) );
    
    insert into example select 0, 'dog', 'Labrador Retriever';
    insert into example select 1, 'deer', 'Whitetail';
    insert into example select 2, 'horse', 'Morgan';
    insert into example select 3, 'horse', 'Tarpan';
    insert into example select 4, 'deer', 'Row';
    insert into example select 5, 'horse', 'Appaloosa';
    insert into example select 6, 'dog', 'German Shephard';
    insert into example select 7, 'horse', 'Thoroughbred';
    insert into example select 8, 'dog', 'Mutt';
    insert into example select 9, 'horse', 'Welara Pony';
    insert into example select 10, 'dog', 'Cocker Spaniel';
    insert into example select 11, 'deer', 'American Elk/Wapiti';
    insert into example select 12, 'horse', 'Shetland Pony';
    insert into example select 13, 'deer', 'Chinese Water Deer';
    insert into example select 14, 'deer', 'Fallow';
    

提交回复
热议问题