首页 > 试题广场 >

分析不同门店各类商品的库存情况和销售情况

[编程题]分析不同门店各类商品的库存情况和销售情况
  • 热度指数:332 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
【背景】:一家连锁超市需要分析不同门店各类商品的库存情况和销售情况。
【原始表】:
stores(门店)表:
  • store_id (门店 ID): 门店的唯一标识符
  • store_name (门店名称): 门店的名称
  • location (门店位置): 门店所在的地址
products(商品)表:
  • product_id (商品 ID): 商品的唯一标识符
  • product_category (商品类别): 商品所属的类别
  • product_name (商品名称): 商品的名称
sales_inventory(销售库存)表:
  • sales_inventory_id (销售库存 ID): 销售库存的唯一标识符
  • store_id (门店 ID): 门店的唯一标识符,用于关联门店表中的门店
  • product_id (商品 ID): 商品的唯一标识符,用于关联商品表中的商品
  • inventory_quantity (库存数量): 商品的库存数量
  • sales_amount (销售额): 商品的销售额

【要求】:根据上面这三个表格,查询每个门店库存数量小于 10 且销售额超过 5000 的商品类别、库存数量和销售额。查询出来的数据先按照门店 ID 升序排列,再按照产品ID 升序排列。要求查询出来的表格的字段如下:
  • store_id: 门店的唯一标识符。
  • store_name: 门店的名称。
  • product_category: 商品类别。
  • inventory_quantity: 库存数量。
  • sales_amount: 销售额。
【示例】:
stores(门店)表:

products(商品)表:
sales_inventory(销售库存)表:
【按要求查询出来的表】
【解释】:上述表中门店A三种产品都有,但是数量小于 10 且销售额超过 5000 的商品只有产品ID1和3,所以关于门店A查询出来的数据有两条。
示例1

输入

DROP TABLE IF EXISTS stores;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS sales_inventory;
-- 创建表
CREATE TABLE stores (
    store_id INT PRIMARY KEY,
    store_name VARCHAR(50),
    location VARCHAR(100)
);

CREATE TABLE products (
    product_id INT PRIMARY KEY,
    product_category VARCHAR(50),
    product_name VARCHAR(100)
);

CREATE TABLE sales_inventory (
    sales_inventory_id INT PRIMARY KEY,
    store_id INT,
    product_id INT,
    inventory_quantity INT,
    sales_amount DECIMAL(10, 2)
);

-- 插入数据
INSERT INTO stores (store_id, store_name, location)
VALUES (1, '门店 A', '地址 A'),
       (2, '门店 B', '地址 B');

INSERT INTO products (product_id, product_category, product_name)
VALUES (1, '食品', '面包'),
       (2, '日用品', '洗发水'),
       (3, '服装', 'T 恤');

INSERT INTO sales_inventory (sales_inventory_id, store_id, product_id, inventory_quantity, sales_amount)
VALUES (1, 1, 1, 8, 6000),
       (2, 2, 2, 15, 4000),
       (3, 1, 3, 5, 7000),
       (4, 2, 3, 5, 8000),
       (5, 1, 2, 15, 10000);

select * from stores;
select * from products;
select * from sales_inventory;

输出

store_id|store_name|product_category|inventory_quantity|sales_amount
1|门店 A|食品|8|6000.00
1|门店 A|服装|5|7000.00
2|门店 B|服装|5|8000.00
select s.store_id,
       s.store_name,
       p.product_category,
       i.inventory_quantity,
       i.sales_amount

from stores as s
left join sales_inventory as i
on s.store_id=i.store_id
left join products as p
on i.product_id=p.product_id

where i.inventory_quantity<10
 and  i.sales_amount>5000
order by s.store_id,p.product_id

发表于 2025-06-27 16:39:50 回复(0)
select
store_id,store_name,product_category,inventory_quantity,sales_amount
from (
    select store_id,product_id,inventory_quantity,sales_amount
    from sales_inventory
    where inventory_quantity < 10
    and sales_amount > 5000
)a
join products using(product_id)
join stores using(store_id)
order by store_id,product_id
发表于 2025-06-24 11:43:24 回复(0)