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.