我知道以前曾经问过这个问题,但我似乎无法找到合适的解决方案。
我有这些数据:
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
我只想要每个Label
的最新版本。这是理想的:
Label StartDate ActivityKey
------------------------------------------------------------------
LABELS 2010-11-01 C266A254-2A3D-4A37-8281-AE9EA08ED086
MASTER BOXES 2010-11-01 9DAD9F77-46FD-4694-9168-E4E5FE306B7D
感谢您提供任何提示
(顺便说一句,这是SQL Server 2008)
答案 0 :(得分:8)
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
也可以使用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
答案 1 :(得分:1)
这也是另一种选择...... :)
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