如果某些列值在SQL中紧接在后,则将行分组

问题描述

如果ids是一个一个的尝试,请按照以下方式进行操作:

select * into #tab from(
    select 0 as id, 'bob' as name, 'note' as event, '14:20' as time union
    select 1, 'bob', 'time', '14:22' union
    select 2, 'bob', 'time', '14:40' union
    select 3, 'bob', 'time', '14:45' union
    select 4, 'bob', 'send', '14:48' union
    select 5, 'bob', 'time', '15:30' union
    select 6, 'bob', 'note', '15:35' union
    select 7, 'bob', 'note', '18:00'
) t

select t.*
from #tab t
left join #tab t1 on t.id = t1.id + 1 and t1.event = t.event 
    -- and t1.name = t.name -- if there are more names you are going to need this one as well
where t1.id is null

结果:

id  name    event   time
0   bob     note    14:20
1   bob     time    14:22
4   bob     send    14:48
5   bob     time    15:30
6   bob     note    15:35

如果ids不是一个一个的,则可以使它们成为:

select identity(int, 1, 1) as id, name, event, time 
into #tab_ordered_ids
from #tab order by name, id, time

解决方法

我正在使用MS SQL Server 2008,并且我想这样做:

+------+--------+--------+------------+
| id   | Name   | Event  | Timestamp  |
+------+--------+--------+------------+
|    0 | bob    | note   | 14:20      |
|    1 | bob    | time   | 14:22      |
|    2 | bob    | time   | 14:40      |
|    3 | bob    | time   | 14:45      |
|    4 | bob    | send   | 14:48      |
|    5 | bob    | time   | 15:30      |
|    6 | bob    | note   | 15:35      |
|    7 | bob    | note   | 18:00      |
+------+--------+--------+------------+

要成为这个:

+------+--------+--------+------------+
| id   | Name   | Event  | Timestamp  |
+------+--------+--------+------------+
|    0 | bob    | note   | 14:20      |
|    1 | bob    | time   | 14:22      |
|    4 | bob    | send   | 14:48      |
|    5 | bob    | time   | 15:30      |
|    6 | bob    | note   | 15:35      |
+------+--------+--------+------------+

即,行由“事件”列“分组”。每个 分组的 相同“事件”中仅显示一个。

  • 如果一个事件(例如ID为0的“ note”)在表中没有紧靠其前后(具有最近时间戳记的行)的行,且具有相等的“ event”值,则显示该事件;
  • 如果同一事件有多个行,例如ID为1-3的“时间”。出现在彼此之后(即没有带有不同“事件”的行具有在它们之间的时间戳),它们中的任何一个都被显示(对我而言无关紧要,所有其他列都是相同的)。

这两个是唯一的规则。