假设你是一家电商平台的数据分析师,你有三个表格:orders、customers和products。 orders表格包含订单信息,包括order_id(订单ID)、customer_id(顾客ID)、product_id(产品ID)和order_date(订单日期)等字段。orders示例数据表如下: customers表格包含顾客信息,包括customer_id(顾客ID)和customer_name(顾客姓名)等字段。customers示例数据表如下: products表格包含产品信息,包括product_id(产品ID)和product_name(产品名称)等字段。products示例数据表如下: 你的任务是编写一条SQL查询语句,找出每个顾客购买的最新产品名称,并按照顾客ID进行排序。
示例1
输入
drop table if exists customers;
-- 创建 customers 表
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(50)
);
drop table if exists products;
-- 创建 products 表
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50)
);
drop table if exists orders;
-- 创建 orders 表
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
product_id INT,
order_date DATE
);
-- 插入 customers 表数据
INSERT INTO customers (customer_id, customer_name)
VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie');
-- 插入 products 表数据
INSERT INTO products (product_id, product_name)
VALUES
(1, 'iPhone'),
(2, 'iPad'),
(3, 'MacBook');
-- 插入 orders 表数据
INSERT INTO orders (order_id, customer_id, product_id, order_date)
VALUES
(1, 1, 1, '2022-01-01'),
(2, 1, 2, '2022-01-02'),
(3, 2, 1, '2022-02-01'),
(4, 2, 3, '2022-02-02'),
(5, 3, 2, '2022-03-01');
输出
customer_id|customer_name|latest_order
1|Alice|iPad
2|Bob|MacBook
3|Charlie|iPad
加载中...