【问题标题】:How to join two tables and get the data如何连接两个表并获取数据
【发布时间】:2020-11-22 20:39:52
【问题描述】:

我有两张表,如下所示。

表#1:客户组表:

No    Reg                     Name 
----------------------------------------
111   Account Owner           Josh
111   Customer Group          Josh Group

表 #2:客户表:

No    Name            Address
----------------------------------
111   Josh Ltd        Lala Land

如何编写一个返回如下所示数据的查询:

No      Customer    Account_Owner  Customer_Group
--------------------------------------------------
111     Josh ltd    Josh           Josh Group

请帮忙

【问题讨论】:

    标签: sql pivot inner-join aggregate-functions


    【解决方案1】:

    使用条件聚合:

    select c.no, c.name as customer,
        max(case when cg.reg = 'Account Owner'  then name end) as account_owner,
        max(case when cg.reg = 'Customer Group' then name end) as customer_group
    from customer c
    inner join customer_group cg on cg.no = c.no
    group by c.no, c.name
    

    【讨论】:

    • 非常完美,非常感谢它的工作,在我不得不在 group by 子句中添加 cg.reg 之前,它没有对它们进行分组,在添加 max 之后它工作了
    • 完成,只是为了了解如何添加 max,group by 不要求添加 cg.reg ?
    • @Sam:case 表达式完成了这项工作。组中只有(或:最多)一行与每个 case 条件匹配,因此您确实得到了您想要的 name
    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    相关资源
    最近更新 更多