【问题标题】:SQL help for inner query内部查询的 SQL 帮助
【发布时间】:2014-04-07 12:57:57
【问题描述】:

很抱歉重新发布,但这将帮助您更好地理解 scnario- 对于每个成员,可以有两种类型的地址(邮件和法律——基于两个差异指标)。我的目标是提取两个地址并将它们显示在每个成员 ID 的一列中。

表 1

Address_key(PK)  Country  City      PostCode
1                UK       London    1111
2                US       New York  2222
3                Spain    Madrid    3333
4                France   Paris     4444
5                Swiss    Munich    5555

表 2

Member Key(PK)   Memebr ID
1                1
2                2
3                3
4                2

Table3

Address Key   Member Key    Mail Ind   Legal Ind
1             1             Y          N
2             1             N          Y
3             2             Y          Y
4             4             N          Y
5             4             Y          N

我的目标是获取每个会员 ID 的邮件地址(基于邮件 ind)和法定地址(基于法律 ind)。 所以我的输出应该是 -

Member Key   Member ID   Country   City    Postcode   Legal Country   Legal City   Legal Postcode
1            1           UK        London  1111       US              New York     2222
2            2           Spain     Madrid  3333       Spain           Madrid       3333         
4            2           Swiss     Munich  5555       France          Paris        4444

谁能帮助如何实现这一目标?我正在使用 oracle 10m toad 9.0
哪个更好用:内部查询还是简单连接?

【问题讨论】:

标签: sql oracle10g toad


【解决方案1】:

类似下面的东西?通过您的列命名,我对 Table2 Member Key(PK) 、 Memebr ID 以及它们与 Table 3 Member ID 的关系感到有些困惑。我的最佳猜测如下:

Select [Member Key], t2.[Member Id], t1.*
FROM TABLE2 t2
INNER JOIN TABLE3 t3 on t3.[Member Key] = t2.[Member Id]
INNER JOIN TABLE1 t1 on t1.[Address Key] = t3.[Address Key]

【讨论】:

    【解决方案2】:

    由于您有两种类型的地址,您可以将两次加入 TABLE3,一次用于邮寄地址,下一次用于法定地址。

    select T2.Member_Key, T2.Member_id
           ,coalesce(T1A.Country,''), coalesce(T1A.City,''), coalesce(T1A.PostCode,'')
           ,coalesce(T1B.Country,''), coalesce(T1B.City,''), coalesce(T1B.PostCode,'')
    from Table2 T2
    left join Table3 T3A on T2.Member_Key=T3A.Member_Key and T3A.Mail_Ind='Y'
    left join Table1 T1A on T3A.Address_key = T1A.Address_Key
    left join Table3 T3B on T2.Member_Key=T3B.Member_Key and T3B.Legal_Ind='Y'
    left join Table1 T1B on T3B.Address_key = T1B.Address_Key
    

    另一种方法是加入一次并使用 CASE 表达式,因此:

    select T2.Member_Key, T2.Member_id
           ,max(coalesce(CASE T3.Mail_Ind='Y'  then T1.Country Else '' End,''))
           , ... etc.
           ,max(coalesce(CASE T3.Legal_Ind='Y' then T1.Country Else '' End,''))
           , ... etc.
    from Table2 T2
    left join Table3 T3 on T2.Member_Key=T3.Member_Key 
    left join Table1 T1A on T3.Address_key = T1.Address_Key
    group by Member_Key, Member_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2021-01-31
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多