【问题标题】:SQL How to select from multiple values in joined tableSQL如何从连接表中的多个值中进行选择
【发布时间】:2021-02-09 22:51:35
【问题描述】:

我有两个表 A 和 B 加入了一个共同的 id 字段。表 A 每个 id 有一个条目。表 B 每个 id 有多个条目。表 B 有两列“名称”和“客户类型”。 我希望能够从 A 和 B 中选择列,但我想将表 B 中的列“名称”显示三次:每次单独匹配 customertype 一次。

例子:

我希望能够选择和显示:

id,country,name(from EC),date,name(from T1),name(from T2)

我该怎么做?我是 SQL 新手!提前感谢您的建议。

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。

标签: sql join select conditional-statements


【解决方案1】:

您可以使用条件聚合:

select a.id, a.country, a.date,
       max(case when customertype = 'EC' then name end) as ec,
       max(case when customertype = 'T1' then name end) as t1,
       max(case when customertype = 'T2' then name end) as et2
from a join
     b
     on a.id = b.id
group by a.id, a.country, a.date

【讨论】:

    【解决方案2】:

    您可以join 并使用条件聚合:

    select a.id, a.country, a.date,
        max(case when b.customertype = 'EC' then name end) name_ec,
        max(case when b.customertype = 'T1' then name end) name_t1,
        max(case when b.customertype = 'T2' then name end) name_t2
    from tablea a 
    inner join tableb b on b.id = a.id
    group by a.id, a.country, a.date
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多