表格和样本数据:
CREATE TABLE orders(
order_id INT NOT NULL,
created_at DATE NOT NULL,
country CHAR(10),
total_net_revenue INT NOT NULL,
total_gross_revenue INT NOT NULL,
total_quantity INT NOT NULL
);
INSERT INTO orders VALUES
(101,'2018-03-08',"China",150,250,20),
(102,'2018-03-08',"China",140,280,67),
(103,'2018-03-08',"China",150,190,15),
(111,'2018-02-09',"China",150,190,15),
(104,'2018-03-07',"China",150,190,15);
CREATE TABLE products_inventory(
product_id INT NOT NULL,
product_name CHAR(10),
brand_name CHAR(10),
purchase_price INT NOT NULL,
selling_price INT NOT NULL,
units_remaining_in_inventory INT NOT NULL
);
INSERT INTO products_inventory VALUES
(97,"3ds","Nintendo",100,250,40),
(98,"Switch","Nintendo",140,280,102),
(99,"Mini","Nintendo",40,190,30),
(131,"Fail","Nintendo",40,190,1310);
CREATE TABLE items_in_order(
order_id INT NOT NULL,
country CHAR(10),
brand CHAR(10),
product_name CHAR(10),
product_ID INT NOT NULL,
net_revenue INT NOT NULL,
gross_revenue INT NOT NULL,
quantity INT NOT NULL
);
INSERT INTO items_in_order VALUES
(101,"China","Nintendo","3ds",97,150,250,20),
(102,"China","Nintendo","Switch",98,140,280,67),
(103,"China","Nintendo","Mini",99,150,190,15),
(111,"China","Nintendo","Fail",131,150,190,15),
(104,"China","Nintendo","3ds",97,150,250,20);
查询:
SELECT i1.product_name, i1.product_id, i1.brand,
SUM(i1.net_revenue) AS net_revenue_last7days,
(p2.selling_price - p2.purchase_price) AS item_margin,
remaining_stock
FROM items_in_order i1
INNER JOIN(
SELECT o1.order_id,o1.country,SUM(o1.total_net_revenue) AS net_revenue,
SUM(o1.total_gross_revenue) AS gross_revenue
FROM orders o1
WHERE (created_at >= NOW() - INTERVAL 7 DAY) AND o1.country = "China"
GROUP BY 1,2
) o2
ON o2.order_id = i1.order_id AND o2.country = i1.country AND o2.net_revenue = i1.net_revenue
AND o2.gross_revenue = i1.gross_revenue
INNER JOIN(
SELECT product_id, product_name, brand_name AS brand, purchase_price, selling_price,
SUM(units_remaining_in_inventory) AS remaining_stock
FROM products_inventory p1
GROUP BY 1,2,3
) p2
ON i1.product_id = p2.product_id AND i1.product_name = p2.product_name AND i1.brand = p2.brand
WHERE i1.country = "China" AND i1.brand = "Nintendo"
GROUP BY 1,2,3
ORDER BY 4 DESC
LIMIT 10
我试图通过加入表格来获得每个品牌每个产品过去7天的收入总和:order& items_in_order。
我的INNER JOIN有问题吗?它应显示3ds过去7天的净收入为300。
其他信息我想要实现的目标:
答案 0 :(得分:1)
第一个JOIN
的这一部分阻止了#104的订单:
AND o2.gross_revenue = i1.gross_revenue
订单#104的orders
表中的总收入为190
,但在250
表中为items_in_order
。
如果您从JOIN
中删除了net_revenue_last7days = 300
。