SQL Server 2012 - Generate query from one table to another involving 3 (three) tables at once

Asked

Viewed 26 times

1

Hello, Community!

I need help with the logic of a consultation I have to do on SQL Server 2012.

Well, I have three tables: [1'] operacao_apf; [2] operacao_contrato; and, [3] operacao_detalhe.

What I need to do: in [1'], I need to take the name of any operation, and, by name, I have to go in [2] and select all contracts related to this operation. After selecting all contracts in [2] related to the transaction researched on 1, i need to go into [3] and select all the details related to each contract of [2] related to the 1.

Scheme:

inserir a descrição da imagem aqui

Note that tables are always associated with 1:N from left to right. An operation can have multiple contracts and each contract can have multiple details.

What I want to do is generate a report with this, but I need to understand the logic of SQL Server 2012 to get started.

1 answer

1


User the INNER JOIN sql.

Specifies all matching row pairs returned. Discards the corresponding rows of both tables. When no junction type is specified, this is the default.

FULL [ OUTER ] Specifies that a row in the left or right table that does not meet the join condition is included in the result set, and the output columns corresponding to the other table are set to NULL. This occurs beyond all lines normally returned by INNER JOIN.

LEFT [ OUTER ] Specifies that all rows in the left table that do not meet the join condition are included in the result set, and the output columns of the other table are set to NULL in addition to all rows returned by the internal join. RIGHT [OUTER] Specifies that all rows in the right table that do not meet the join condition are included in the result set, and the output columns that correspond to the other table are set to NULL, in addition to all rows returned by the internal join.

Specifies that the SQL Server query optimizer uses a join hint, or an execution algorithm, for each query specified in the FROM clause of the query. For more information, see join tips (Transact-SQL). JOIN Indicates that the specified merge operation must happen between specified table sources or views.

ON Specifies the criterion on which the junction is based. The criteria can specify any predicate, although comparison columns and operators are often used, for example:

SELECT *  
FROM operacao_apf AS o   
JOIN operacao_contrato AS c  
ON o.ProductID = c.ProductID -- altere com os ids derelação  
JOIN operacao_detalhe AS d  
ON c.ProductID = d.ProductID -- altere com os ids derelação  
  • 1

    Perfect! Thank you very much! It worked!

Browser other questions tagged

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