/* Table Sales */
CREATE TABLE sales (
id int auto_increment primary key,
product VARCHAR(255),
KPI VARCHAR(255),
sales_volume INT
);
INSERT INTO sales
(product, KPI, sales_volume)
VALUES
("Product A", "sold", "500"),
("Product A", "sold", "300"),
("Product B", "sold", "200"),
("Product C", "sold", "300"),
("Product D", "sold", "900");
/* Table Logistics */
CREATE TABLE logistics (
id int auto_increment primary key,
product VARCHAR(255),
KPI VARCHAR(255),
quantity INT
);
INSERT INTO logistics
(product, KPI, quantity)
VALUES
("Product A", "outbound", "800"),
("Product B", "outbound", "100"),
("Product B", "outbound", "400"),
("Product C", "outbound", "250"),
("Product D", "outbound", "900");
预期结果:
product value_in_sales value_in_logistics differnce_of_values
Product A 800 800 0
Product B 200 500 300
Product C 300 250 -50
Product D 900 900 0
在上面的示例中,我有两个名为sales
and的表logistics
。
我的目标是将表格中的sales_volume
KPI与表格中的 KPI 进行比较。sold
sales
quantity
outbound
logistics
我尝试使用,UNION ALL
但它只对两个表的值进行排序,而不像预期的结果那样比较它们。
SELECT
product,
KPI,
SUM(sales_volume)
FROM sales
GROUP BY 1
UNION ALL
SELECT
product,
KPI,
SUM(quantity)
FROM logistics
GROUP BY 1
我需要在查询中进行哪些更改才能获得预期的结果?