SQL Server displays the latest update data for each category and SQL updates

Source: Internet
Author: User

SQL Server displays the latest update data for each category and SQL updates

This example describes how SQL Server displays the latest data updates for each category. We will share this with you for your reference. The details are as follows:

In a project, you may often find the latest data of each category, for example, the latest data of a certain category. This SQL statement is recorded here:

-- ===================================================== ====== -- Author: <Rising_Sun> -- creation date: <2012-9-28> -- Description: <display the newest n data records under each category> -- ================================ ======================== DECLARE @ t TABLE (NewsId INT, newsType NVARCHAR (20), NewsTitle NVARCHAR (50), AddTime DATETIME) insert into @ t VALUES (1, 'Sports News', 'Rocket wins ', '2017-10-11 ') insert into @ t VALUES (2, 'Sports news ', 'Liu Xiang exited due to injury', '2017-10-12 ') insert into @ t VALUES (3, 'Sports news ', 'sha', '2017-10-13 ') insert into @ t VALUES (4, 'gossip News', 'fengjie married', '2017-10-11 ') insert into @ t VALUES (5, 'gossip News', 'andy Lau when the foo', '2017-10-12 ') insert into @ t VALUES (6, 'gossip News ', 'Mr Cang came to China to publicize ', '2017-10-13') insert into @ t VALUES (7, 'Financial news ', 'stocks fell below 2011 point ', '2017-10-12 ') insert into @ t VALUES (8, 'Financial news', 'First interest rate cut in RMB ', '2017-10-10 ') -- the newest display quantity of each category: DECLARE @ ShowNums INTSET @ ShowNums = 2 SELECT * FROM (SELECT NewsId, NewsTitle, NewsType, AddTime, ROW_NUMBER () OVER (partition by NewsType order by AddTime DESC) AS RowIndex FROM @ t) as twhere RowIndex <= @ ShowNums

Run the SQL statement and the result is:

I hope this article will help you design SQL Server database programs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.