用SUM和COUNT连接两个表

时间:2018-07-24 13:38:30

标签: mysql-5.5

我正在尝试联接两个表,并同时获得SUM和COUNT。我需要从历史记录表中获取SUM QTY,从旋转表中获取每个PN和LOC的COUNT SN。

历史记录表:

create table history (
        code int(10) primary key,
    PN varchar(10) not null,
        LOC varchar(10) not null,
    Qty int(10) not null);

insert into history values (1,  'T1',   'AAA',  1);
insert into history values (2,  'A1',   'BBB',  2);
insert into history values (3,  'J1',   'CCC',  3);
insert into history values (4,  'A2',   'AAA',  1);
insert into history values (5,  'J2',   'BBB',  2);
insert into history values (6,  'A3',   'CCC',  3);
insert into history values (7,  'J3',   'AAA',  4);
insert into history values (8,  'T1',   'BBB',  5);
insert into history values (9,  'A1',   'CCC',  1);
insert into history values (10, 'J2',   'AAA',  3);
insert into history values (11, 'J2',   'BBB',  4);
insert into history values (12, 'A1',   'CCC',  3);
insert into history values (13, 'J2',   'AAA',  5);

轮值表

create table rota (
        code int(10) primary key,
    PN varchar(10) not null,
    SN varchar(10) not null,
        LOC varchar(10) not null);

insert into rota values (1, 'T1',   't1a', 'AAA');
insert into rota values (2, 'A1',   'a1a',  'BBB');
insert into rota values (3, 'J1',   'j1a',  'CCC');
insert into rota values (4, 'A2',   'a2a',  'AAA');
insert into rota values (5, 'J2',   'j2a',  'BBB');
insert into rota values (6, 'A3',   'a3a',  'CCC');
insert into rota values (7, 'J3',   'j3a',  'AAA');
insert into rota values (8, 'T1',   't1b',  'BBB');
insert into rota values (9, 'A1',   'a1b',  'CCC');
insert into rota values (10,    'J2',   'j2b',  'AAA');
insert into rota values (11,    'J2',   'j2c',  'BBB');
insert into rota values (12,    'A1',   'a1c',  'CCC');
insert into rota values (13,    'J2',   'j2d',  'AAA');
insert into rota values (14,    'J2',   'j2e',  'AAA');
insert into rota values (15,    'J2',   'j2f',  'AAA');

所需的结果是下表

 PN      LOC     SUM(QTY)    COUNT(SN) 
 A1      BBB         2          1
 A1      CCC         4          2
 A2      AAA         1          1
 A3      CCC         3          1
 J1      CCC         3          1
 J2      AAA         8          4
 J2      BBB         6          2
 J3      AAA         4          1
 T1      AAA         1          1
 T1      BBB         5          1

1 个答案:

答案 0 :(得分:1)

使用子查询,如下所示:

select a.pn, a.loc, a.q, b.c from 
  (select h.pn, h.loc, sum(qty) q from history h group by h.pn, h.loc) a
  join
  (select r.pn, r.loc, count(sn) c from rota r group by r.pn, r.loc) b
  on a.pn = b.pn and a.loc = b.loc
  order by a.pn;

(在Oracle上试用过,目前没有MySQL,但它应该可以正常工作或稍作修改)