T-SQL合并具有相似日期时间的行对

时间:2012-03-07 21:16:35

标签: tsql merge

是否可以合并具有相似(<500毫秒)日期时间值的行对,并保留原样的其他行?

我有以下事件表:

ID    DateTime                  FileName  Event
=================================================
001   2011-04-04 12:30:15.000   File_A    Deleted
002   2011-04-04 15:30:37.000   File_A    Created
003   2011-04-05 08:30:25.000   File_A    Deleted
004   2011-04-05 08:30:25.050   File_A    Created

如果我在500毫秒的时间跨度内有一对Deleted和Created事件,查询应该合并这两行,并将Event设置为“Modified”。

结果应该是:

DateTime                  FileName  Event
============================================
2011-04-04 12:30:15.000   File_A    Deleted
2011-04-04 15:30:37.000   File_A    Created
2011-04-05 08:30:25.000   File_A    Modified

提前致谢..

2 个答案:

答案 0 :(得分:0)

试试这个:

select cast(DATEPART(hour, DateColumn) as varchar(2)) + ':' + cast(DATEPART(minute, DateColumn) as varchar(2)) + ':' + cast(DATEPART(second, DateColumn) as varchar(2)) as DateTime,
max(filename) as FileName, Max(event) as event
from table
group by 
cast(DATEPART(hour, DateColumn) as varchar(2)) + ':' + cast(DATEPART(minute, DateColumn) as varchar(2)) + ':' + cast(DATEPART(second, DateColumn) as varchar(2)) as DateTime

答案 1 :(得分:0)

SELECT t1.DateTime, t1.FileName, 'Modified' as Event
FROM Table t1
JOIN Table t2 ON DATEDIFF(millisecond, t1.DateTime, t2.DateTime) < 500
              AND t1.Event = 'Deleted' AND t2.Event = 'Created'
UNION ALL
SELECT t3.DateTime, t3.FileName, t3.Event
FROM Table t3 
WHERE NOT EXISTS(SELECT 1 
                 FROM Table t4
                 JOIN Table t5 ON DATEDIFF(millisecond, t4.DateTime, t5.DateTime) < 500
                               AND t4.Event = 'Deleted' AND t5.Event = 'Created' 
                               AND t3.ID IN (t4.ID, t5.ID)
)

...好吧,必须有更好的方法来取回非合并的结果。但是这个应该工作吗?