在SQL Server 2000中合并两行或更多行

时间:2011-04-21 08:09:57

标签: sql sql-server database sql-server-2000

假设我的表包含以下信息:

row | ID  |       date1          |        date2            | place   | value
--------------------------------------------------------------------------
1   |  1  |  2011-01-23 05:33:21 |    2011-01-23 06:43:10  |    A    |     5
2   |  1  |  2011-01-23 06:44:21 |    2011-01-23 07:13:28  |    A    |     4
3   |  1  |  2011-01-23 07:14:21 |    2011-01-23 07:27:28  |    A    |     4
4   |  1  |  2011-01-23 08:30:11 |    2011-01-23 09:56:45  |    A    |     6
5   |  1  |  2011-01-23 09:58:21 |    2011-01-23 10:43:26  |    B    |     8
6   |  2  |  2011-01-23 05:33:21 |    2011-01-23 06:43:21  |    A    |     3

我想像第1行和第2行那样合并,如下所示。(表中有如此多的行,如上所述)条件为DATEDIFF(minute, row1.date2, row2.date1) < 10 and row1.place = row2.place

row | ID  |       date1          |        date2          |  place   | value
=======================================================================
1   |  1  |  2011-01-23 05:33:21 |   2011-01-23 07:27:28 |     A    |    13
2   |  1  |  2011-01-23 08:30:11 |   2011-01-23 09:56:45 |     A    |    6
3   |  1  |  2011-01-23 09:58:21 |   2011-01-23 10:43:26 |     B    |    8
4   |  2  |  2011-01-23 05:33:21 |   2011-01-23 06:43:21 |     A    |    3

请帮我从我的桌子上选择上面的结果。

提前致谢。

1 个答案:

答案 0 :(得分:0)

insert into table
   select 
      row, id, date1, date2, place, sum(value)
   from table
   where (your date diff condition)
   group by row, id, date1, date2, place

我认为这应该有效.. :)