Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

SQL Server: Get data from record with max date / newest date

I am using the following stored procedure to get the newest date out of a column which works fine.

Can someone tell me how I have to amend this that I also get the rest of the data of this record selected (i.e. the one with the max date) ? The column in question is called "updated" and is formatted as datetime so the values there should be unique.

Example: The max value for column "updated" is the row with "itemID" = 3. In this case I also want the rest of the data in this row selected, say the columns are called col1, col2, col3, col4 + the column "updated".

My stored procedure:

SET NOCOUNT ON;
SELECT      CONVERT(VARCHAR(11), MAX(updated), 106) AS lastUpdated
FROM        MeetingDetails
WHERE       itemStatus = 'active'
FOR XML PATH('updates'), ELEMENTS, TYPE, ROOT('root')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could take the analytic approach:

SELECT *
FROM   (SELECT col1, col2, col3, col4, 
               RANK() OVER (PARTITION BY col1, col2, col3 
                            ORDER BY updated DESC) AS rk
        FROM   MeetingDetails
        WHERE  itemstatus = 'active') t
WHERE  rk = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...