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:
Desired:
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
Lucas Miranda, your suggestion will work only if the fields are
int
?– Rodrigo
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
– Lucas Miranda
I’ll check in the morning, and about each customer having only one
doc_original
, may happen to have more than one case, eachdoc_original
originating other documents. I did not remember to include this in the example.– Rodrigo
in fact did not work, in your suggestion, is it possible to get around this? http://sqlfiddle.com/#! 18/616d5/1
– Rodrigo
Most complete example ( with more situations) http://sqlfiddle.com/#! 18/806e15/1
– Rodrigo