【发布时间】:2017-11-27 07:56:09
【问题描述】:
我有以下格式的三个表格:
表_1
Plan_ID Plan_Code Plan_Description Location_ID
1 A Plan A 1
Table_2(当前为行)
ID Plan_ID Procedure_ID Discount
表_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
所以我需要编写一个查询,它在传递 Plan_Id 时输出以下结果,并且还通过匹配表 1 和 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
同样在 Table_2 中,如果我们有交叉引用行
ID Plan_ID Procedure_ID Discount
1 1 2 5
下面应该是查询输出:
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
到目前为止我已经尝试过:
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
但是由于where 条件,查询不输出任何结果,但是当我在第一次连接中替换where 条件时,我得到不正确的输出。我尝试使用不同的表序列和连接选项运行查询,但未能成功。
【问题讨论】: