Sql 具有多个子句的Partition by和order by

Sql 具有多个子句的Partition by和order by,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一些通话数据,这些数据被分为单独的部分,详细描述了通话过程的各个部分。 因此,对于一个调用,它可能有3个段,如下表中的CallData_段 Destination Number / Call Type / Service Nos / Unique Call ID / Start DateTime / End DateTime 234 4 14 666 22082020 01:00 2208202001:01 234 4 15 666

我有一些通话数据,这些数据被分为单独的部分,详细描述了通话过程的各个部分。 因此,对于一个调用,它可能有3个段,如下表中的CallData_段

   Destination Number  / Call Type / Service Nos / Unique Call ID / Start DateTime / End DateTime 
    234 4   14  666       22082020 01:00    2208202001:01 
    234 4   15  666       22082020 01:00    22082020 01:01 
    234 5   12  666       22082020 01:03    22082020 01:04 
    234 3   13  666       22082020 01:04    22082020 01:06
 
这些规则是:

  • 不要对只有一个段的任何调用进行分区–排除
  • 对于具有多个段的调用,它们需要按调用进行分区 类型=5(已转移)以及最早和最新的服务id需求 要针对每个段进行记录
因此,对于上述示例,预期输出如下(2段):


我尝试了一些行号与分区和order by的组合,并加入到同一个表中,但没有成功。有什么想法吗?

没有样本数据。。。像这样的

;with partitions_cte as (
    select *, row_number() over (partition by [Unique Call ID] order by [Start DateTime]) rn
    from CallData_Segments)
select *
from partitions_cte
where
  [Call Type]=5
  or rn=1
  and [Unique Call ID] not in(select [Unique Call ID] 
                              from CallData_Segments
                              group by [Unique Call ID]
                              having count(*)=1);

让我们看看你的尝试。
;with partitions_cte as (
    select *, row_number() over (partition by [Unique Call ID] order by [Start DateTime]) rn
    from CallData_Segments)
select *
from partitions_cte
where
  [Call Type]=5
  or rn=1
  and [Unique Call ID] not in(select [Unique Call ID] 
                              from CallData_Segments
                              group by [Unique Call ID]
                              having count(*)=1);