我要:
谢谢您的帮助!
delete from 02_inventory.tempinvsummary;
insert into 02_inventory.tempinvsummary
(select pn,
sum(if(tp='Coil',no,0)) as 'coil',
sum(if(tp='Blank',no,0)) as 'blank',
sum(if(tp='Press',no,0)) as 'press',
sum(if(tp='Assy',no,0)) as 'assy' ,
sum(if(tp='Robot',no,0)) as 'robot'
from inventory
group by pn);
insert into 02_inventory.tempinvsummary
(select pn,
sum(if(tp='Coil',no,0)) as 'suplcoil',
sum(if(tp='Blank',no,0)) as 'suplblank',
sum(if(tp='Press',no,0)) as 'suplpress',
sum(if(tp='Assy',no,0)) as 'suplassy' ,
sum(if(tp='Robot',no,0)) as 'suplrobot'
from suplinventory
group by pn)
on duplicate key update
'====================
'prbly need codes here
coil=coil+suplcoil ????
'====================
select * from 00_masterdata.itemmaster, 02_inventory.tempinvsummary
where 00_masterdata.itemmaster.pn= 02_inventory.tempinvsummary.pn;
答案 0 :(得分:0)
假设您的表格看起来像这样
drop table if exists tempinvsummary, inventory, suplinventory;
create table tempinvsummary (pn int primary key, col1 int);
create table inventory (pn int , col1 int);
create table suplinventory (pn int , col1 int);
insert into tempinvsummary values (1,null),(2,null);
insert into inventory values (1,10),(1,10),(3,10);
insert into suplinventory values (2,10);
您可以合并并汇总2个表,然后像这样测试和更新重复表
insert into tempinvsummary (pn,col1)
select pn,
sum(case when src = 'i' then col1 else 0 end) + sum(case when src ='s' then col1 else 0 end) netcol1
from
(
select 'i' as src,i.pn,i.col1 from inventory i
union all
select 's' as src,s.pn,s.col1 from suplinventory s
) s
group by pn
on duplicate key
update col1 = values(col1);
结果
+----+------+
| pn | col1 |
+----+------+
| 1 | 20 |
| 2 | 10 |
| 3 | 10 |
+----+------+
3 rows in set (0.00 sec)
但是我不相信您是否需要一个临时表,如果您只需要将其连接到00_masterdata.itemmaster
例如
select masterdata.username,pn,netcol1
from users as masterdata
join
(
select pn,
sum(case when src = 'i' then col1 else 0 end) + sum(case when src ='s' then col1 else 0 end) netcol1
from
(
select 'i' as src,i.pn,i.col1 from inventory i
union all
select 's' as src,s.pn,s.col1 from suplinventory s
) s
group by pn
) a
on a.pn = masterdata.id;
我在数据库中使用方便的表(称为用户)的地方来说明这一点
结果
+----------+------+---------+
| username | pn | netcol1 |
+----------+------+---------+
| John | 1 | 20 |
| Jane | 2 | 10 |
| Ali | 3 | 10 |
+----------+------+---------+
3 rows in set (0.01 sec)