当我用总和连接两个表时,我的代码无法正常工作。
第一张桌子
create table table1 (
code int(10) primary key,
PN varchar(10) not null,
LOC varchar(10) not null,
Stock int(10) not null);
insert into table1 values (1,'T1','AAA',2);
insert into table1 values (2,'A1','AAA',2);
insert into table1 values (3,'J1','AAA',3);
insert into table1 values (4,'A2','AAA',1);
insert into table1 values (5,'J2','BBB',2);
insert into table1 values (6,'A3','BBB',3);
insert into table1 values (7,'J3','BBB',4);
insert into table1 values (8,'T1','BBB',5);
insert into table1 values (9,'A1','BBB',1);
insert into table1 values (10,'J2','CCC',3);
insert into table1 values (11,'J2','DDD',4);
insert into table1 values (12,'A1','DDD',3);
insert into table1 values (13,'J2','EEE',5);
insert into table1 values (14,'A1','AAA',15);
第二张桌子
create table table2 (
code int(10) primary key,
PN varchar(10) not null,
LOC varchar(10) not null,
Used int(10) not null,
Year int(10));
insert into table2 values (1,'T1','AAA',2, 2018);
insert into table2 values (2,'A1','AAA',2, 2018);
insert into table2 values (3,'J1','AAA',3,2017);
insert into table2 values (4,'A2','AAA',1,2018);
insert into table2 values (5,'J2','BBB',2,2017);
insert into table2 values (6,'A3','BBB',3,2017);
insert into table2 values (7,'J3','BBB',4,2016);
insert into table2 values (8,'T1','BBB',5,2016);
insert into table2 values (9,'A1','BBB',1,2018);
insert into table2 values (10,'J2','CCC',3,2018);
insert into table2 values (11,'J2','DDD',4,2018);
insert into table2 values (12,'A1','DDD',3,2018);
insert into table2 values (13,'J2','EEE',5,2017);
insert into table2 values (14,'A1','AAA',15,2018);
我想在所有位置以以下格式打印结果。我可以按以下方式获取总计,但是当我使用CASE时,它会重复值。
+------+----+-----+-------+------------+------------+
| code | PN | LOC | Stock | counttotal | TotalStock |
+------+----+-----+-------+------------+------------+
| 2 | A1 | AAA | 2 | 16 | 84 |
| 4 | A2 | AAA | 1 | 1 | 1 |
| 5 | J2 | BBB | 2 | 8 | 28 |
| 1 | T1 | AAA | 2 | 2 | 7 |
+------+----+-----+-------+------------+------------+
SELECT a.*,
Count(b.Used) as counttotal,
sum(a.Stock) TotalStock
FROM table1 a
LEFT JOIN table2 b on a.PN=b.PN WHERE b.Year > 2017
GROUP BY a.PN
ORDER BY a.PN ASC;
但是,与所有LOC的总计相反,我希望在正下方的列中包含正确的数据。
+----+----------+-----------+----------+-----------+
| PN | AAA_Used | AAA_Stock | BBB_Used | BBB_Stock |
+----+----------+-----------+----------+-----------+
| A1 | 68 | 68 | 4 | 4 |
| A2 | 1 | 1 | 0 | 0 |
| J2 | 0 | 0 | 0 | 4 |
| T1 | 4 | 2 | 0 | 5 |
+----+----------+-----------+----------+-----------+
SELECT a.PN
,SUM(CASE WHEN b.LOC = "AAA" THEN b.Used ELSE 0 END) AS "AAA_Used"
,SUM(CASE WHEN a.LOC = "AAA" THEN a.Stock ELSE 0 END) AS "AAA_Stock"
,SUM(CASE WHEN b.LOC = "BBB" THEN b.Used ELSE 0 END) AS "BBB_Used"
,SUM(CASE WHEN a.LOC = "BBB" THEN a.Stock ELSE 0 END) AS "BBB_Stock"
FROM table1 a
LEFT JOIN table2 b on a.PN=b.PN WHERE b.Year > 2017
GROUP BY a.PN, b.PN
ORDER BY a.PN ASC;