开发者

How do I grab the most recent rows when the keys are all different?

I know this has been asked before but I can't seem to find a solution that fits.

I have this data:

Label           StartDate     ActivityKey
------------------------------------------------------------------
LABELS          2009-02-12    23D645CA-7F05-47FF-9AC4-1414DCBF44DD
LABELS          2010-11-01    C266A254-2A3D-4A37-8281-AE9EA08ED086
MASTER BOXES    2009开发者_开发知识库-02-12    81DBEA52-B7BC-4861-96B4-7A77A2D7F07B
MASTER BOXES    2010-11-01    9DAD9F77-46FD-4694-9168-E4E5FE306B7D

I only want the most recent for each Label. This is desired:

Label           StartDate     ActivityKey
------------------------------------------------------------------
LABELS          2010-11-01    C266A254-2A3D-4A37-8281-AE9EA08ED086
MASTER BOXES    2010-11-01    9DAD9F77-46FD-4694-9168-E4E5FE306B7D

Thanks for any tips

(BTW, this is SQL Server 2008)


SELECT label, StartDate, ActivityKey
    FROM (SELECT label, StartDate, ActivityKey,
                 ROW_NUMBER() OVER (PARTITION BY label ORDER BY StartDate DESC) AS RowNum
              FROM YourTable
         ) t
    WHERE t.RowNum = 1

The same query can also be done with a CTE:

WITH cteRowNum AS (
    SELECT label, StartDate, ActivityKey,
           ROW_NUMBER() OVER (PARTITION BY label ORDER BY StartDate DESC) AS RowNum
        FROM YourTable
)
SELECT label, StartDate, ActivityKey
    FROM cteRowNum
    WHERE RowNum = 1


This is also an alternative..:)

Select T.label, T.StartDate, T1.ActivityKey From
(
    Select label, Max(StartDate) as StartDate
    From YourTable
    Group By label
)T
Inner Join YourTable T1 on T1.Label = T.Label and T1.StartDate = T.StartDate
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜