基于时间关联数据库记录

Relating database records based on time

我想根据大致理解的业务规则对行进行分组

我有以下格式的约会数据。

约会 Table 看起来像这样

ID| AppointmentTime         | Appointment                           |Client ID
23| 2019-09-30 09:15:00.000 | Project meeting :Taylor, James        | NULL  
34| 2019-09-30 09:20:00.000 | Project meeting :Taylor, James        | NULL
35| 2019-09-30 09:25:00.000 | Project meeting :Taylor, James        | NULL
36| 2019-09-30 10:25:00.000 | Pre sales : Hayes, John               | 2
47| 2019-09-30 10:30:00.000 | Project meeting :Manning, Richard     |425
50| 2019-09-30 14:30:00.000 | Closure meeting :Kuruvita, Peter      | NULL

客户 Table 看起来像这样

ID  | Last Name | First Name 
2   | Hayes     | John               
425 | Manning   |Richard
3   | Taylor    | James

我希望能够根据以下规则对约会进行分组

预期结果如下所示

ClientID |Clint Name            |Appointment Start      | Appointment End        | Appointment Destail
NULL     |Peter  Kuruvita       |2019-09-30 14:30:00.000|2019-09-30 14:34:00.000 |Closure meeting
3        |James Taylor          |2019-09-30 09:15:00.000|2019-09-30 09:29:00.000 |Project meeting 
2        |John  Hayes           |2019-09-30 10:25:00.000|2019-09-30 10:29:00.000 |Pre sale  
425      |Richard Manning       |2019-09-30 10:30:00.000|2019-09-30 10:34:00.000 |Project meeting

你能帮忙写一个 SQL 语句或不同部分的片段,以便我将它们拼凑起来吗?

在 Microsoft SQL Server 2008 R2 (SP2) 中实现。

您可以根据相邻的槽合并表格,并使用间隙和孤岛的行号差异方法获得已知个客户端名称。

select clientid,
       (firstname + ' ' + lastname) as name,
       min(appointment_start),
       max(appointment_end)
from (select a.*,
             row_number() over (order by appointment_start) as seqnum,
             row_number() over (partition by clientid order by appointment_start) as seqnum_c             
      from appointment a
     ) a left join
     clients c
     on a.clientid = c.id
group by (seqnum - seqnum_c), a.clientid, c.lastname, c.firstname;

注意:这假定同一客户的相邻时段是同一预约。如果你想拆分它们,你真的需要将你的数据库升级到支持的 SQL 服务器版本,这样你就可以使用 lag() 和其他功能。

对于您的示例数据,您也可以只使用约会名称:

select clientid,
       (firstname + ' ' + lastname) as name,
       min(appointment_start),
       max(appointment_end)
from appointment a left join
     clients c
     on a.clientid = c.id
group by a.appointment, a.clientid, c.lastname, c.firstname;