1

Let suppose my database data structure is like that

ShopId   Transaction

001       1.000    
001       2.000
001       3.000
002       1.000
002       2.000
002       3.000

Now it is might possible that some transaction are missing let suppose

002       4.000
002       6.000

In above table 5.000 transaction of table is missing.

I want to write a query that find the missing sequence number like above in my database.

So my query will return result

   shopid     transaction
   002       5.000

1 Answer 1

2

To get the number of missing transactions per ShopId:

  SELECT ShopId
       , count(*) 
           - max([Transaction])
           + min([Transaction])
           - 1 as MissingTranCount
    FROM yourtable
GROUP BY ShopId

To get the missing transactions:

1.Generate table #numbers

2.Generate #shops:

  SELECT ShopId as id
    into #shops
    FROM yourtable
GROUP BY ShopId
  HAVING count(*) 
           - max([Transaction])
           + min([Transaction])
           - 1 > 0

3.Get the missing transactions:

  SELECT id
       , number
    FROM #numbers
   cross join #shops shops
   WHERE exists (SELECT 1
                   FROM yourtable
                  WHERE ShopId = id
                    and number < [Transaction]
                )
     and exists (SELECT 1
                   FROM yourtable
                  WHERE ShopId = id
                    and number > [Transaction]
                )
     and not exists (SELECT 1
                       FROM yourtable
                      WHERE ShopId = id
                        and number = [Transaction]
                )         
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.