OP 没有提供 DDL 表,也没有提供insert 语句的样本集,所以有一些假设:
-
StartDate 是一个 varchar() (为了这个答案;应该能够毫无问题地切换到 date、datetime 或 datetime)
-
EndDate 在所需的输出中不需要(根据 OP 的示例输出)
-
(ClientId, StartDate) 的组合是唯一的(否则建议的答案 - 下面 - 不会产生预期的结果)
样本数据:
create table clients
(ClientId varchar(10) null
,StartDate varchar(10) null
,EndDate varchar(20) null
)
go
insert into clients values ('A', '20180101', null)
insert into clients values ('A', '20190101', null)
insert into clients values ('A', '20200101', null)
insert into clients values ('B', '20180101', null)
insert into clients values ('B', '20190101', null)
insert into clients values ('C', '20190101', null)
insert into clients values ('C', '20200101', null)
go
正如@Impaler 所提到的,Sybase ASE 不支持“窗口函数”,所以我们需要有点创意。
使用自联接的一个想法:
select c1.ClientId,
c1.StartDate,
count(*) as num
from clients c1
join clients c2
on c1.ClientId = c2.ClientId
and c1.StartDate >= c2.StartDate
group by c1.ClientId, c1.StartDate
order by 1,2
go
ClientId StartDate num
---------- ---------- -----------
A 20180101 1
A 20190101 2
A 20200101 3
B 20180101 1
B 20190101 2
C 20190101 1
C 20200101 2
注意:对于较大的数据集和/或没有有用索引的情况下,此查询可能表现不佳,ymmv ...
演示如果(ClientId, StartDate) 对不是唯一的会发生什么...
假设我们的数据集如下所示:
insert into clients values ('A', '20180101', null)
insert into clients values ('A', '20190101', null)
insert into clients values ('A', '20200101', null)
insert into clients values ('B', '20180101', null)
insert into clients values ('B', '20190101', null) -- duplicate (ClientId, StartDate)
insert into clients values ('B', '20190101', null) -- duplicate (ClientId, StartDate)
insert into clients values ('C', '20190101', null)
insert into clients values ('C', '20200101', null)
go
建议的查询生成:
ClientId StartDate num
---------- ---------- -----------
A 20180101 1
A 20190101 2
A 20200101 3
B 20180101 1
B 20190101 6 -- oops, only 2 rows for 'B' and the wrong 'num' value for this row
C 20190101 1
C 20200101 2
如果建议的查询在 OP 的环境中不起作用,则 OP 可能需要提供minimal, reproducible example;特别是,提供示例create table 和insert into 语句以充分展示真实数据集。