我有两张额外的桌子并保存所有表格,他们有一个列销售
Table extra Table save
ITEMS SALES ITEMS SALES
A 15 A 7
B 20 B 2
A 2 A 5
B 2 B 2
我想首先按项目对元素进行分组,然后从表格中的销售列中减去表格中的一列销售额,并将结果放入另一个包含列的订单表(项目差异) 结果应该是这样的
Table order
ITEMS difference
A 5
B 18
答案 0 :(得分:0)
试试这个:
SELECT T1.ITEMS,T1.extraSales-T2.saveSales as Difference FROM
(SELECT ITEMS,SUM(SALES) as extraSales FROM extra GROUP BY ITEMS) T1
INNER JOIN
(SELECT ITEMS,SUM(SALES) as saveSales FROM save GROUP BY ITEMS) T2
ON T1.ITEMS=T2.ITEMS
结果:
ITEMS DIFFERENCE
A 5
B 18
修改强>
将其插入另一张桌子:
INSERT INTO orderTable VALUES
(
SELECT T1.ITEMS,T1.extraSales-T2.saveSales as Difference FROM
(SELECT ITEMS,SUM(SALES) as extraSales FROM extra GROUP BY ITEMS) T1
INNER JOIN
(SELECT ITEMS,SUM(SALES) as saveSales FROM save GROUP BY ITEMS) T2
ON T1.ITEMS=T2.ITEMS
)