快速行合并后更新
表1(卡位记录)
p d t
001 2007-01-01 07:30
001 2007-01-01 12:31
001 2007-01-01 12:30
001 2007-01-02 13:30
002 2007-01-01 07:30
002 2007-01-01 12:30
003 2007-01-03 07:30
表2(结果)
p d t1 t2 t3 ....
001 2007-01-01 07:30 12:31
002 2007-01-01 07:30 12:30
001 2007-01-02 13:30
003 2007-01-03 07:30
说明:(兼容sql2000&2005)
表1中数据按p和d分组,
多行合并为一行时,如果有卡位就按先后顺序插入到表2中
(5分钟之内只选其中第一个[t1]或最后一个[t2])
如果表2中t为单数就选其中第一个,
如果表2中t是双数就选其中最后一个,t字段一共有10个左右
用游标的方法太慢了,因为数据量太大
[解决办法]
--如果間隔5分鐘有多條數據,這裡取的是第一條。
--創建測試環境
Create Table 表1
(p Char(3),
d Varchar(10),
t Varchar(5))
Insert 表1 Select '001 ', '2007-01-01 ', '07:30 '
Union All Select '001 ', '2007-01-01 ', '12:31 '
Union All Select '001 ', '2007-01-01 ', '12:30 '
Union All Select '001 ', '2007-01-02 ', '13:30 '
Union All Select '002 ', '2007-01-01 ', '07:30 '
Union All Select '002 ', '2007-01-01 ', '12:30 '
Union All Select '003 ', '2007-01-03 ', '07:30 '
GO
--測試
Select * Into #T1 From 表1 A
Where Not Exists(Select p From 表1 Where p = A.p And d = A.d And DateDiff(mi, d + ' ' + t, A.d + ' ' + A.t) Between 0 And 5 And t != A.t)
Select OrderID = (Select Count(p) From #T1 Where p = A.p And d = A.d And t <= A.t), * Into #T2 From #T1 A
Declare @S Varchar(8000)
Select @S = 'Select p, d '
Select @S = @S + ', Max(Case OrderID When ' + Cast(OrderID As Varchar) + ' Then t Else ' ' ' ' End) As t ' + Cast(OrderID As Varchar)
From #T2 Group By OrderID
Select @S = @S + ' From #T2 Group By p, d '
EXEC(@S)
Drop Table #T1, #T2
GO
--刪除測試環境
Drop Table 表1
--結果
/*
pdt1t2
0012007-01-0107:3012:30
0022007-01-0107:3012:30
0012007-01-0213:30
0032007-01-0307:30
*/