T-SQL - Receive the gap between 2 Numbers

会有一股神秘感。 提交于 2021-02-05 08:02:54

问题


I'm using SQL Server 2012.

I'm receiving a "Max Number" f.e. 201900005 this tells me the range starts at 201900000 (this is given). Now i want to receive the numbers which are missing in this range.

I've looked at several Questions about this, but i can't seem to get it working. Checking the table against itself, using between or using a cursor.

Max Number = 201900005, Min Number = 201900000
test_table
+----------------+
|   test_number  |
+----------------+
|   201900001    |
|   201900003    |
|   201900004    |
+----------------+
result
+----------------+
|    missing     |
+----------------+
|   201900000    |
|   201900002    |
|   201900005    |
+----------------+

The current process works with a "helping"-table which essentally contains all numbers between 201900000 and 201900005 (a lot more in the real situation) and compares those to the onces in the test_table.

I would be grateful for any suggestions.


回答1:


Personally, I would would use a Tally to create a list of all the possible numbers, and then LEFT JOIN that list to your table and return rows where there is no match:

CREATE TABLE dbo.Test_Table (Test_Number int);
INSERT INTO dbo.Test_Table (Test_Number)
VALUES(201900001),(201900003),(201900004);
GO

DECLARE @Start int = 201900000,
        @End int = 201900005;

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (@End - @Start +1) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 + @Start AS I
    FROM N N1, N N2, N N3) --1000 rows, if you need more, just add more
SELECT T.I
FROM Tally T
     LEFT JOIN dbo.Test_Table TT ON T.I = TT.Test_Number
WHERE TT.Test_Number IS NULL;

GO

DROP TABLE dbo.Test_Table;

DB<>Fiddle




回答2:


Just another option using an ad-hoc tally table and a Union ALL

Example

Declare @R1 int = 201900000
Declare @R2 int = 201900005

Select Missing = N
 From  (
        Select Top (@R2-@R1+1) N=@R1-1+Row_Number() Over (Order By (Select NULL)) From  master..spt_values n1, master..spt_values n2 
        Union All
        Select test_number from test_table Where test_number between @R1 and @R2
       ) A
 Group By N
 Having count(*)=1

Returns

Missing
201900000
201900002
201900005


来源:https://stackoverflow.com/questions/58187731/t-sql-receive-the-gap-between-2-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!