MYSQL - Detect sequential break with conditional

Asked

Viewed 347 times

1

Hello I need help to make a query or process to detect gaps in a numerical field, I have a table of tax notes, which has a field num_nfe, it must follow a sequence, there can be no gaps in the numbering and I must check in another field, the status field.

The query should check which records do not exist and also which records have the status field other than "Issued" or "Cancelled".

I’m trying something like this:

SELECT j1.num_nfe +1 AS id
FROM nfe j1
LEFT JOIN nfe j2 ON j2.num_nfe = j1.num_nfe +1
WHERE j2.num_nfe IS NULL 
AND (
DATE_FORMAT( j1.dt_emissao,  '%Y-%m-%d' ) 
BETWEEN  '2018-03-01'
AND  '2018-04-30'
)  AND status in('Cancelada','Emitida')
AND j1.num_nfe <> ( 
SELECT MAX( num_nfe ) 
FROM nfe) 
ORDER BY j1.num_nfe
  • 1

    Can you give us a picture of how you are and how you’d like it to be, just to get a better look at the problem?

  • I tried to do something like this: SELECT j1.num_nfe +1 AS id&#xA;FROM nfe j1&#xA;LEFT JOIN nfe j2 ON j2.num_nfe = j1.num_nfe +1&#xA;WHERE j2.num_nfe IS NULL &#xA;AND (&#xA;DATE_FORMAT( j1.dt_emissao, '%Y-%m-%d' ) &#xA;BETWEEN '2018-03-01'&#xA;AND '2018-04-30'&#xA;) AND status in('Cancelada','Emitida')&#xA;AND j1.num_nfe <> ( &#xA;SELECT MAX( num_nfe ) &#xA;FROM nfe) &#xA;ORDER BY j1.num_nfe

  • you can edit your question to show what you have tried and the scenario. So it is easier to view.

  • select * from nfe Where not exists (select null from nfe nfe2 Where nfe2.num_nfe -1 = nfe.num_nfe) -- there is no previous

  • There is no previous one, but if for example a difference interval with more than one number is inserted it does not detect, for example, if someone instead of typing 10, typing 100 does not show from 11 to 99 for example. and also does not work in case of records that exist but are with different status.

  • https://forum.imasters.com.br/topic/237229-falha-na-numera%C3%A7%C3%A3o/ another solution for Oracle , rownum is a pseudo column that I don’t think exists in Mysql

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.