如何解决如果某些列值在SQL中紧接在后,则将行分组
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
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的“时间”。出现在彼此之后(即没有带有不同“事件”的行具有在它们之间的时间戳),它们中的任何一个都被显示(对我而言无关紧要,所有其他列都是相同的)。
这两个是唯一的规则。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。