Find document that originated the following

Asked

Viewed 59 times

0

I have a table where a document can originate new documents, and this new document loads in a column the number of the originating document (not necessarily the first document that ever existed).

There may be several documents after the originator, but I always need to find the first document. In the example document 112 generated 117, which generated 119, which generated 120, which generated 121, but the originator of everything, is 112.

I attached images to try to make more clear what I want to do, also script to create the table and an attempt to achieve the goal.

Table:

Tabela

Desired:

inserir a descrição da imagem aqui

Link files

I’d appreciate it if you could help.

The ideal would be independent of how many documents there are I manage to reach the originator, but if I have to do for a fixed amount of documents, I believe it also serves the purpose. Even about the title of the question, I could not think of something better. I accept criticism to be able to make more coherent with the need.

attempt:

 SELECT cliente,num_doc,num_doc_anterior,
 (SELECT( IIF((num_doc_anterior =''),(num_doc),
 (IIF((num_doc_anterior<>''),
 (select num_doc from DADOS where num_doc =dd.num_doc_anterior),
 'XXX'))))) AS doc_original
 FROM DADOS dd

1 answer

1

Assuming that each customer has only one doc_original you could do it like this:

WITH    q AS 
        (
        SELECT  *
        FROM    dados
        WHERE   num_doc_anterior IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate
        UNION ALL
        SELECT  m.*
        FROM    dados m
        JOIN    q
        ON      m.num_doc = q.num_doc_anterior
        )
SELECT  d.*, q.num_doc as doc_original
FROM    q inner join dados d on
q.cliente = d.cliente

link to the sqlfiddle with the example

  • Lucas Miranda, your suggestion will work only if the fields are int?

  • 1

    no, I did int in Fiddler because I didn’t know the type of your data, remembering that if the client id has more than one doc_original, this Join will not go well

  • I’ll check in the morning, and about each customer having only one doc_original, may happen to have more than one case, each doc_original originating other documents. I did not remember to include this in the example.

  • in fact did not work, in your suggestion, is it possible to get around this? http://sqlfiddle.com/#! 18/616d5/1

  • Most complete example ( with more situations) http://sqlfiddle.com/#! 18/806e15/1

Browser other questions tagged

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