MySQL Inner加入过去7天内找到最畅销的产品

时间:2018-03-08 22:02:12

标签: mysql sql

sqlfiddle.com/#!9/ecede/1

表格和样本数据:

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。

其他信息我想要实现的目标:

  • 过去7天内任天堂在中国的每项最高收入
  • 显示每个项目的当前库存的单位
  • 显示每个项目的保证金

1 个答案:

答案 0 :(得分:1)

第一个JOIN的这一部分阻止了#104的订单:

AND o2.gross_revenue = i1.gross_revenue

订单#104的orders表中的总收入为190,但在250表中为items_in_order

如果您从JOIN中删除了net_revenue_last7days = 300

http://sqlfiddle.com/#!9/ecede/10