简体   繁体   中英

How to select at most N records for a given value of a column in a table?

I have a table called NewsArticles having columns ID, LanguageID, Date, Title, ArticleContent. I want to create a view which selects the 5 most recent news articles of each language in the database.

For example, if I have 3 languages, say, English, French and German, the query should return 15 records, containing the 5 latest English news articles, the 5... you get the picture. How can I construct such a query?

For each unique LanguageID in NewsArticles, return top 5 records ordered by Date descending.

It's pretty simple with CTE.

;with x as 
(
    select ID, LanguageID, Title, Date,
            row_number() over ( partition by LanguageID order by Date DESC  ) as position
    from NewsArticles
)
select * from x 
where Position < 6
CREATE VIEW Top5Articles
AS     
    SELECT top 5 * FROM LatestNews WHERE LanguageID = 1 order by createdontime desc // latest 5 English news articles
    union
    SELECT top 5 * FROM LatestNews WHERE LanguageID = 2 order by createdontime desc
    union
    SELECT top 5 * FROM LatestNews WHERE LanguageID = 3 order by createdontime desc

Assuming you have a createdontime column with the article created on time.

union will give you all the selects back in one result set.

Do you want something like this -

select *
from LatestNews
where (
   select count(*) from LatestNews as A
   where A.LanguageID = LatestNews.LanguageID 
) <= 5 order by Date DESC;

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