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

不羁的心 提交于 2019-12-25 02:13:29

问题


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')

回答1:


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



回答2:


SELECT col1, col2, col3, col4, updated
FROM   MeetingDetails 
WHERE  updated in (
    SELECT      MAX(updated)
    FROM        MeetingDetails
    WHERE       itemStatus = 'active'
)

This should be what you're looking for. From here, if you need to narrow it down further, just add more criteria to your where clause.




回答3:


Here is the query:

set nocount on;

select 
   md.col1, 
   md.col2,
   -- ......
   convert(varchar(11), md.updated, 106) as lastUpdated
from
   MeetingDetails md
where
   md.itemStatus = 'active'
   and md.updated = (select max(updated)
                     from MeetingDetails
                     where itemStatus = 'active')
for xml path('updates'), elements, type, root('root')

Based on how many records have the max(updated) this select may return more than one row and hence this query could return multiple nodes.




回答4:


A simple TOP 1 clause with an ORDER BY should work for you.

SELECT TOP 1 col1, col2, col3, col4,
       updated
FROM   @MeetingDetails 
WHERE  itemStatus = 'active'
ORDER BY
      updated DESC
FOR XML PATH('updates'), ELEMENTS, TYPE, ROOT('root')


来源:https://stackoverflow.com/questions/21911553/sql-server-get-data-from-record-with-max-date-newest-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!