SQL in propagated data

Asked

Viewed 65 times

0

I need to hit the SQL below for the database Oracle.

The idea is to retrieve the code from the table Produto associated with the table code Matriz.

In this structure, the Matriz is related to at least one Filial and this contains the link to Produto. But a Filial may have a Filial, that may have a Filial, etc..

That is, to access the related codes in the tables Produto and Matriz, I need a backward propagation of existing information in the relational table Filial, which I resolved with the START WITH and CONNECT BY PRIOR.

I succeeded by testing the sub-select below separately with an example record. But I can’t extract all the records.

I tried to do it this way (I hope you’re not confused), but subselect doesn’t see the external table.

select produto.nome, produto.qtde, tabelaAux.codigo from produto
  left join (select * from
    (select matriz.codigo as codMatriz, matriz.codFilial as codFilial
    from matriz
    left join filial on filial.codC = matriz.codigo
    start with filial.codA = produto.codigo          --falha aqui
    connect by prior filial.codigoPai = filial.codigo)
  where codMatriz is not null)
  tabelaAUX on tabelaAUX.codFilial = produto.codFilial;
  • I recommend you use the site http://sqlfiddle.com, put the base structure with some data, we can help you

  • I do not understand because in general CONNECT BY is used for SQL S recursives , a classic example is the functio (matricula,nome,matricula_do_superior) https://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm

1 answer

1

Have you tried that?

SELECT PRODUTO.NOME,
PRODUTO.QTDE,
TABELAAUX.CODIGO,
TABELAAUX.NOME_MATRIZ,
TABELAAUX.NOME_FILIAL
FROM PRODUTO
LEFT JOIN
(
    SELECT MATRIZ.CODIGO AS CODMATRIZ,
      MATRIZ.NOME AS NOME_MATRIZ,
      FILIAL.NOME AS NOME_FILIAL,
      MATRIZ.CODFILIAL    AS CODFILIAL,
      FILIAL.CODA,FILIAL.CODIGO,FILIAL.CODIGOPAI 
    FROM MATRIZ
    LEFT JOIN FILIAL   ON FILIAL.CODC= MATRIZ.CODIGO
    WHERE MATRIZ.CODIGO                   IS NOT NULL
) TABELAAUX ON TABELAAUX.CODFILIAL = PRODUTO.CODFILIAL
START WITH TABELAAUX.CODA            = PRODUTO.CODIGO 
CONNECT BY NOCYCLE PRIOR TABELAAUX.CODIGOPAI = TABELAAUX.CODIGO; 

What should the data structure look like? I did not understand the relationship between the tables.

inserir a descrição da imagem aqui

  • 1

    This link may be a good suggestion, but your reply will not be valid if one day the link crashes. In addition, it is important for the community to have content right here on the site. It would be better to include more details in your response. A summary of the content of the link would be helpful enough! Learn more about it in this item of our Community FAQ: We want answers that contain only links?

  • Ok...I’m a new user and I’m still learning how the system works.

  • Quiet Samuel, now your answer is much clearer

Browser other questions tagged

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