【问题标题】:Access - Join two tables on two fields, get all records from table AAccess - 在两个字段上连接两个表,从表 A 中获取所有记录
【发布时间】:2014-04-25 12:53:44
【问题描述】:

好的,所以在 MS Access 中,我尝试在两个字段(客户 ID 和产品类型)上连接两个表,让表 A 使用每种产品类型的总和,并拥有表 A 中的所有记录,这样我就可以知道表 B 中缺少什么。

在表 A 中,每个客户对每个产品类型的年份都有多条记录。但在表 B 中,每种产品类型只有一条记录。在表 B 中,并非所有产品类型都在那里。

示例表:

表 A:

Cust ID    ProdType   Year   Number
   1          A       2014     5
   1          A       2013     8
   1          B       2014     3
   2          A       2014    13
   2          C       2014     2
   3          B       2014     1
   3          C       2014     4

表 B:

                             Number 
    Cust ID    ProdType     Arrived
       1          A            5
       2          A           13
       2          C            2
       3          B            1
       3          C            2

最终结果应如下所示:

                        Sum of    Number
Cust ID    ProdType     Number    Arrived
   1          A           13        5
   1          B            3        
   2          A           13       13
   2          C            2        2
   3          A            1        1
   3          C            4        2

【问题讨论】:

    标签: sql ms-access


    【解决方案1】:

    试试这个,

    MySQL 语法

    select a.cust_id, a.prodtype, sum(a.number), b.arrived
    from table_a a left join table_b b on a.cust_id=b.cust_id and a.prodtype=b.prodtype
    group by a.cust_id, a.prodtype
    

    这里是DEMO (MySQL)

    Ms-Access

    select a.cust_id, a.prodtype, sum(a.number), b.arrived
    from table_a a left join table_b b 
                   on a.cust_id=b.cust_id and
                   on a.prodtype=b.prodtype
    group by a.cust_id, a.prodtype
    

    【讨论】:

    • 完美运行。不知道为什么我无法弄清楚!我必须做的一项更改是按列表将 b.arrived 添加到组中
    • 在 ms-access 中;使用group by子句时,您只能选择column,即group by子句中的group by子句或任何聚合函数计算结果。
    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多