[英]How to check if the previous and next records are sequential in SQL
我有一個包含列的表(ID int,RECEIPT_BARCODE nvarchar(200),FK_CLOSURE bigint)
ID RECEIPT_BARCODE FK_CLOSURE
1 01020011304500190001 58100000010019
2 01020011304500190002 58100000010019
1 01020011404500200001 58100000010020
2 01020011404500200002 58100000010020
3 01020011404500200003 58100000010020
1 01020011504500210001 58100000010021
1 01020011604500220001 58100000010022
1 01020011604500230001 58100000010023
2 01020011604500230002 58100000010023
1 01020011604500250001 58100000010025
3 01020011604500250003 58100000010025
我們的程序會自動將銷售額插入表格中。 該表的插入方式如下; 當FK_CLOSURE向上運行時,ID再次設置為“ 1”(如您在上面看到的),只要FK_CLOSURE不變,它就會連續進行。 當FK_CLOSURE再次更改時,ID設置為“ 1”。
所以問題是; 有時我們的銷售程序會出錯,並且不會插入銷售,但是會增加ID值,如您在最后一行看到的那樣。 在最后一行中,ID從1增加到3,沒有2 ...
我想報告這種失敗。 我嘗試使用CURSOR,但無法管理。 有什么建議么 ?
您可以使用邏輯來比較行號和鍵之間的差異,如果差異發生變化,則ID號中會有一個空洞。 在您的情況下,差異可能應始終為零。 所以像這樣:
create table #test (ID int, RECEIPT_BARCODE nvarchar(200),FK_CLOSURE bigint)
insert into #test values
(1, '01020011304500190001',58100000010019),
(2, '01020011304500190002',58100000010019),
(1, '01020011404500200001',58100000010020),
(2, '01020011404500200002',58100000010020),
(3, '01020011404500200003',58100000010020),
(1, '01020011504500210001',58100000010021),
(1, '01020011604500220001',58100000010022),
(1, '01020011604500230001',58100000010023),
(2, '01020011604500230002',58100000010023),
(1, '01020011604500250001',58100000010025),
(3, '01020011604500250003',58100000010025)
select
ID,
RECEIPT_BARCODE,
FK_CLOSURE,
ID - row_number() over(partition by FK_CLOSURE order by ID asc)
from #test
結果將是:
1 01020011304500190001 58100000010019 0
2 01020011304500190002 58100000010019 0
1 01020011404500200001 58100000010020 0
2 01020011404500200002 58100000010020 0
3 01020011404500200003 58100000010020 0
1 01020011504500210001 58100000010021 0
1 01020011604500220001 58100000010022 0
1 01020011604500230001 58100000010023 0
2 01020011604500230002 58100000010023 0
1 01020011604500250001 58100000010025 0
3 01020011604500250003 58100000010025 1
試試這個查詢
declare @SalesTable table (ID int, RECEIPT_BARCODE nvarchar(200),FK_CLOSURE bigint)
insert into @SalesTable values
(1, '01020011304500190001',58100000010019),
(2, '01020011304500190002',58100000010019),
(1, '01020011404500200001',58100000010020),
(2, '01020011404500200002',58100000010020),
(3, '01020011404500200003',58100000010020),
(1, '01020011504500210001',58100000010021),
(1, '01020011604500220001',58100000010022),
(1, '01020011604500230001',58100000010023),
(2, '01020011604500230002',58100000010023),
(1, '01020011604500250001',58100000010025),
(3, '01020011604500250003',58100000010025)
select
FK_CLOSURE
from @SalesTable
group by FK_CLOSURE
having count(distinct ID) != MAX(ID)
當任何FK_CLOSURE缺少某些ID時,則該FK_CLOSURE的count(distinct ID)
唯一count(distinct ID)
小於MAX(ID)
輸出
FK_CLOSURE
58100000010025
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.