合并数据范围值

时间:2010-10-08 15:00:43

标签: tsql

在每分钟的时间间隔内,我想在SQL表中合并值以压缩空间。如果我有一个包含以下值的表:

UserId Value Date
1      2     10/08/2010 10:30:00
1      2     10/08/2010 10:30:10
1      2     10/08/2010 10:30:20
1      2     10/08/2010 10:30:30
1      2     10/08/2010 10:30:40
1      2     10/08/2010 10:30:50
1      2     10/08/2010 10:31:00
1      2     10/08/2010 10:31:10
1      2     10/08/2010 10:31:20
1      2     10/08/2010 10:31:30
1      2     10/08/2010 10:31:40
1      2     10/08/2010 10:31:50

每分钟,我都希望将值压缩为单个分钟间隔。所以顶部表格如下:

UserId Value Date
1      12     10/08/2010 10:30:00
1      12     10/08/2010 10:31:00

...在运行查询后...之前的值将被删除并替换为新的合并值。

我如何在TSQL中实现这一目标?

2 个答案:

答案 0 :(得分:2)

With RawData As
    (
    Select 1 As UserId, 2 As Value, Cast('10/08/2010 10:30:00' As datetime) As [Date]
    Union All Select 1, 2, '10/08/2010 10:30:10'
    Union All Select 1, 2, '10/08/2010 10:30:20'
    Union All Select 1, 2, '10/08/2010 10:30:30'
    Union All Select 1, 2, '10/08/2010 10:30:40'
    Union All Select 1, 2, '10/08/2010 10:30:50'
    Union All Select 1, 2, '10/08/2010 10:31:00'
    Union All Select 1, 2, '10/08/2010 10:31:10'
    Union All Select 1, 2, '10/08/2010 10:31:20'
    Union All Select 1, 2, '10/08/2010 10:31:30'
    Union All Select 1, 2, '10/08/2010 10:31:40'
    Union All Select 1, 2, '10/08/2010 10:31:50'
    )
Select UserId, Value, DateAdd(s, -DatePart(s, [Date]), [Date])
From RawData
Group By UserId, Value, DateAdd(s, -DatePart(s, [Date]), [Date])

答案 1 :(得分:0)

假设有一个名为Test的表,则以下脚本应该有效。

BEGIN TRANSACTION

UPDATE Test
SET Test.Value = T2.Value
FROM Test
INNER JOIN (
    SELECT UserId, SUM([Value]) as [Value], 
         convert(nvarchar(25), [Date], 100) as [Date]
    FROM Test
    GROUP BY UserId, convert(nvarchar(25), [Date], 100)
) T2 ON Test.UserId = T2.UserId AND Test.[Date] = T2.[Date]
INNER JOIN (
    SELECT UserId, COUNT([Value]) as ValueCount, 
         convert(nvarchar(25), [Date], 100) as [Date]
    FROM Test
    GROUP BY UserId, convert(nvarchar(25), [Date], 100) 
) T3 ON Test.UserId = T3.UserId AND Test.[Date] = T3.[Date] AND ValueCount > 1

DELETE  
FROM Test
WHERE datepart(ss, [Date]) <> 0

COMMIT TRANSACTION

脚本的工作方式是,在一个事务中,它通过总计该分钟的所有值来更新'00'时间的值,如果该分钟范围至少有两个记录(即00秒,10)秒)以便不执行不必要的更新。

然后查询删除所有没有'00'秒的记录,因为它们都将包含在上面的更新中。