我有一個包含名稱和訪問資料的表,如下所示
| 姓名 | 訪問許可日期 | 許可證過期 |
|---|---|---|
| 約翰 | 1/1/2020 | 3/30/2020 |
| 約翰 | 2/1/2020 | 5/2/2020 |
| 約翰 | 6/1/2020 | 2020/9/30 |
| 詹姆士 | 2020/3/15 | 6/14/2020 |
對于此處的每個名稱,如果訪問間隔在 60 天內,我希望結果將訪問許可證日期匯總為一個(第一個),并使用最后一個過期日期作為新的許可證過期日期。如果訪問許可證是在上次之后超過 60 天簽發的,我希望它開始一個新的記錄,因此結果如下:
| 姓名 | 訪問許可日期 | 許可證過期 |
|---|---|---|
| 約翰 | 1/1/2020 | 5/2/2020 |
| 約翰 | 6/1/2020 | 2020/9/30 |
| 詹姆士 | 2020/3/15 | 6/14/2020 |
我想不出解決方案。
uj5u.com熱心網友回復:
您可以使用此存盤程序來獲得預期的結果:
create procedure my_custom_sp
as
create table #tbl (
[name] varchar(20),
[visitlicensedate] date,
[licenseExpiredate] date
)
declare cur cursor for
select [name], [visitlicensedate] from tbl
declare @name varchar(20), @visitlicensedate date
open cur
fetch next from cur into @name, @visitlicensedate
while @@FETCH_STATUS =0
begin
insert into #tbl ([name], [visitlicensedate], [licenseExpiredate])
select [name], min([visitlicensedate]), max([licenseExpiredate])
from tbl t1 where [name] = @name
and [visitlicensedate] < DATEADD(d,60,@visitlicensedate)
and not exists (
select * from #tbl t2 where [name] = @name
and DATEDIFF(d,t2.[visitlicensedate],t1.[visitlicensedate]) < 60
)
group by [name]
fetch next from cur into @name, @visitlicensedate
end
close cur
deallocate cur
select * from #tbl
go
結果
exec my_custom_sp
/*
name visitlicensedate licenseExpiredate
John 2020-01-01 2020-05-02
John 2020-06-01 2020-09-30
James 2020-03-15 2020-06-14
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/371551.html
標籤:sql sql-server 查询语句 缝隙和岛屿
下一篇:根據具有多種組合的兩列值更新列
