SQL Server-选择行,删除重复项,但保留日期最高的行
考虑SQL Server 2008中的以下数据库表:SQL Server-选择行,删除重复项,但保留日期最高的行,sql,sql-server-2008,tsql,Sql,Sql Server 2008,Tsql,考虑SQL Server 2008中的以下数据库表: ActionID (PK) ActionType ActionDate UserID ContentID 1 'Create' '2013-05-26 18:40:00' 1 10 2 'Create' '2013-05-26 18:30:00' 2 10 3 '
ActionID (PK) ActionType ActionDate UserID ContentID
1 'Create' '2013-05-26 18:40:00' 1 10
2 'Create' '2013-05-26 18:30:00' 2 10
3 'Edit' '2013-05-26 12:30:00' 5 12
4 'Edit' '2013-05-26 12:25:00' 5 12
5 'Delete' '2013-05-26 12:22:00' 6 12
我想编写一个SQL查询,按ContentID
和ActionType
进行分组,但返回包含最新ActionDate
的行,忽略其他行,即使它们具有不同的UserID
或其他列值
因此,它应该回报的是:
ActionID (PK) ActionType ActionDate UserID ContentID
1 'Create' '2013-05-26 18:40:00' 1 10
3 'Edit' '2013-05-26 12:30:00' 5 12
5 'Delete' '2013-05-26 12:22:00' 6 12
但是我不太明白如何编写查询来完成它。一种方法是使用CTE(公共表表达式) 使用此CTE,您可以按照某些标准对数据进行分区,即
ContentID
和Actiontype
,并让SQL Server为每个“分区”的所有行编号,从1开始,按ActionDate
排序
因此,请尝试以下方法:
;WITH Actions AS
(
SELECT
ActionID, ActionType, ActionDate, UserID, ContentID,
RowNum = ROW_NUMBER() OVER(PARTITION BY ContentID, ActionType ORDER BY ActionDate DESC)
FROM
dbo.YourTable
WHERE
......
)
SELECT
ActionID, ActionType, ActionDate, UserID, ContentID,
FROM
Actions
WHERE
RowNum = 1
ORDER BY
ActionDate DESC
这接近你想要的吗
select t1.*
from Table1 t1
inner join (select ContentID, ActionType, max(ActionDate) as MaxDate
from Table1
group by ContentID, ActionType) t2
on t1.ContentID = t2.ContentID
and t1.ActionType = t2.ActionType
and t1.ActionDate = t2.MaxDate;
如果{ContentID,ActionType}对有重复的行,任何回答您问题的查询都可能产生意外结果。它不会让我在WITH Actions位中坚持ORDER BY,但我可以将其放在后一个SELECT语句中。我需要按ActionDate列排序,那么这是一种有效的方法吗?@SundayIronfoot:只需将
order by
添加到从CTE中选择行的“外部”SELECT
(如我更新的响应中所示)-这就是您需要的吗?