2

我正在尝试为现有表数据编写查询。TABLE_A 和 TABLE_B 有 1 条记录,但 TABLE_C 有 2 条记录。一个用于家庭地址,另一个用于工作地址。

因此,以下查询返回 2 条记录。我试图从 2 条记录中只获得 1 条记录。

如果 CITY 为 NULL,则 address_type = 1(Home) 的 state_id 为 null 然后获取 Work(address_type = 2) 地址。如果两者都为空,则获取“家庭”地址。实现此功能的最佳方法是什么。

谢谢你的任何建议。

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

A_ID int
B_ID int 
A_Desc  varchar(20)

表_B

B_ID int
first_name  varchar(30)
last_name   varchar(30)

表_C

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
4

4 回答 4

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
于 2012-06-27T19:03:22.750 回答
0

只需将此逻辑构建到表 b 和 c 的左连接的连接条件中。

如果 CITY 为 NULL,则 address_type = 1(Home) 的 state_id 为 null 然后获取 Work(address_type = 2) 地址。如果两者都为空,则获取“家庭”地址

于 2012-06-27T19:09:03.337 回答
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
于 2012-06-27T19:12:50.990 回答
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 
于 2012-06-27T19:23:56.463 回答