In an unrelated question, I asked Kovid about compacting the database in order to re-number. He informed me that you would never want to re-use the numbers as it could be a major problem.
What you're asking is a similar question and ultimately would get a similar answer. While you could program calibre to perform the operation, it would do so by merging all of the books under one number. All of the merged books would be marked as deleted but the numbering could not be re-used.
The only way around this issue entirely is to have perfect input data to create a perfect calibre library.
I've tried - it is way too difficult, time consuming and frustrating.