Tenho três tabelas no formato abaixo:
Tabela 1
Plan_ID Plan_Code Plan_Description Location_ID
1 A Plan A 1
Tabela_2 (atualmente agora linhas)
ID Plan_ID Procedure_ID Discount
Tabela 3
Procedure_ID Procedure_Name Procedure_Fee Location_ID
1 P1 10 1
2 P2 20 1
3 P3 30 1
4 P3 30 2
Portanto, preciso escrever uma consulta que produza abaixo do resultado quando Plan_Id é passado e também combinando as Tabelas 1 e 3 Location_ID:
Plan_ID Plan_Code ID Procedure_ID Procedure_Name Procedure_Fee Discount
1 A 0 1 P1 10 0
1 A 0 2 P2 20 0
1 A 0 3 P3 30 0
Também na Tabela_2, se tivermos linhas de referência cruzada
ID Plan_ID Procedure_ID Discount
1 1 2 5
Abaixo deve estar o resultado da consulta:
Plan_ID Plan_Code ID Procedure_ID Procedure_Name Procedure_Fee Discount
1 A 0 1 P1 10 0
1 A 1 2 P2 20 5
1 A 0 3 P3 30 0
Até agora eu tentei:
declare @planID int =1
SELECT t1.Plan_ID,
t1.Plan_Code,
t2.ID,
t3.Procedure_ID,
t3.Procedure_Name,
t3.Procedure_Fee,
t2.Discount
FROM table1 tl
LEFT JOIN table2 t2
on t1.Plan_ID=t2.Plan_ID
RIGHT JOIN table3 t3
ON t2.Procedure_ID = t3.Procedure_ID and t1.Location_Id=t3.LocationID
where t1.Plan_Id = @planID
Mas por causa da where
condição, a consulta não produz nenhum resultado, mas quando substituo a where
condição na primeira junção, obtenho uma saída incorreta. Tentei executar a consulta com sequência de tabela diferente e opção de junção, mas não consegui.
Uma vez que a tabela 2 pode ou não ter uma linha correspondente, você precisa lidar com os dados ausentes nas correspondências entre a tabela 1 e a tabela 2:
declare @planID int = 1;
SELECT t1.Plan_ID,
t1.Plan_Code,
if(t2.ID IS NULL,0,t2.ID) as `ID`,
t3.Procedure_ID,
t3.Procedure_Name,
t3.Procedure_Fee,
IF(t2.Discount IS NULL,0,t2.Discount) as `Discount`
FROM table1 tl
JOIN table3 t3
ON t1.Location_Id = t3.LocationID
LEFT JOIN table2 t2
ON t2.Procedure_ID = t3.Procedure_ID and t1.Plan_ID = t2.Plan_ID
where t1.Plan_Id = @planID;
Este artigo é coletado da Internet.
Se houver alguma infração, entre em [email protected] Delete.
deixe-me dizer algumas palavras