我正在尝试编写现有表数据的查询。 TABLE_A和TABLE_B有一条记录,但TABLE_C有2条记录。一个用于家庭住址,另一个用于工作地址。
因此以下查询返回2条记录。我试图从2条记录中只获得一条记录。
如果CITY为NULL,则address_type = 1(Home)的state_id为null,然后获取Work(address_type = 2)地址。如果两者都为null,则获取“Home”地址。实现此功能的最佳方式是什么。
感谢您的任何建议。
select a.A_ID, a.B_ID, a.A_DESC, b.first_name, b.last_name, c.address_type, c.city, c.state
from table_A a
left join table_B b on b.B_ID = a.B_ID
left join table_C c on c.B_id = b.B_id
where a.A_ID = 10
A_ID int
B_ID int
A_Desc varchar(20)
B_ID int
first_name varchar(30)
last_name varchar(30)
C_ID int
B_ID int
address_type int
city varchar(50)
state int
结果:
A_ID B_ID A_DESC first_name last_name address_type city state
--------------------------------------------------------------------------------
10 200 test_ name1 name_last 1 NULL NULL
10 200 test_ name1 name_last 2 City_test 2
我想要这个最终结果
A_ID B_ID A_DESC first_name last_name address_type city state
--------------------------------------------------------------------------------
10 200 test_ name1 name_last 2 City_test 2
答案 0 :(得分:0)
您可以使用outer apply
查找最高类型的地址:
select *
from table_A a
left join
table_B b
on b.B_ID = a.B_ID
outer apply
(
select top 1 *
from table_C c
where c.B_id = b.B_id
order by
case
when c.address_type = 2 and c.city is not null then 1
else c.address_type = 1 and c.city is not null then 2
end
) c
where a.A_ID = 10
答案 1 :(得分:0)
只需将此逻辑构建到左连接到表b和c的连接条件中。
如果CITY为NULL,则address_type = 1(Home)的state_id为null,然后获取Work(address_type = 2)地址。如果两者都为null,则获取“Home”地址
答案 2 :(得分:0)
select a.A_ID, a.B_ID, a.A_DESC, b.first_name, b.last_name,
coalesce(c1.address_type,c2.address_type) address_type,
coalesce(c1.city,c2.city) city,
coalesce(c1.state,c2.state) state
from table_A a
left join table_B b on b.B_ID = a.B_ID
left join table_C c1 on c.B_id = b.B_id and c.Address_Type = 1
left join table_C c2 on c.B_id = b.B_id and c.Address_Type = 2
where a.A_ID = 10
答案 3 :(得分:0)
一般技术:
select distinct a.A_ID
, a.B_ID
, a.A_DESC
, b.first_name
, b.last_name
, coalesce(home.address_type, work.address_type)
, coalesce(home.city,work.city)
, coalesce(home.state, work.state)
from table_A a
left join table_B b on b.B_ID = a.B_ID
left join table_C home on home.B_id = b.B_id and home.address_type = 1
left join table_C work on work.B_id = b.B_id and home.address_type = 2
where a.A_ID = 10