[英]MySQL query | Select latest row from groups
我有一个类似这样的表:
产品编号 | client_id | 类别 | 价格 | 创建日期 |
---|---|---|---|---|
1个 | 1个 | 一种 | 3.1 | 2022-11-01 |
2个 | 1个 | 一种 | 3.2 | 2022-11-02 |
3个 | 1个 | 乙 | 3.3 | 2022-11-03 |
4个 | 1个 | 乙 | 3.4 | 2022-11-04 |
5个 | 2个 | 乙 | 3.5 | 2022-11-05 |
6个 | 2个 | 乙 | 3.6 | 2022-11-06 |
7 | 2个 | 一种 | 3.7 | 2022-11-07 |
8个 | 2个 | C | 3.8 | 2022-11-08 |
我想要 select 从每个 client_id 和类别的最新created_date 的价格,所以我的预期结果是这样的:
产品编号 | client_id | 类别 | 价格 | 创建日期 |
---|---|---|---|---|
2个 | 1个 | 一种 | 3.2 | 2022-11-02 |
4个 | 1个 | 乙 | 3.4 | 2022-11-04 |
6个 | 2个 | 乙 | 3.6 | 2022-11-06 |
7 | 2个 | 一种 | 3.7 | 2022-11-07 |
8个 | 2个 | C | 3.8 | 2022-11-08 |
你能帮我解决这个问题吗? 谢谢
我在这里发现了类似的东西: Select first row in each GROUP BY group?
更新
实际上我想对以下内容做同样的事情(这是一个更现实的例子): https://www.db-fiddle.com/f/fHc6MafduyibJdkLHe9cva/0
预期结果:
val1 | 值2 | num1 | num2 | 创建日期 |
---|---|---|---|---|
X | 一种 | 33 | 333 | 2022-11-03 |
X | 乙 | 66 | 666 | 2022-11-06 |
X | C | 88 | 888 | 2022-11-08 |
X | 丁 | 99 | 999 | 2022-11-09 |
是 | 一种 | 111 | 1111 | 2022-11-11 |
你可以这样做。 使用 MAX 首先获取最新日期,然后按类别和客户 ID 进行分组。
看看这个db_fiddle
SELECT a.pid, b.cid, b.category, a.price, b.created_date FROM products a
JOIN
(SELECT category, cid, MAX(created_date) as created_date FROM products GROUP BY cid, category) as b
ON a.category = b.category AND a.cid = b.cid AND a.created_date = b.created_date
ORDER BY pid
请下次提问时提供DDL + DML命令,这样其他人就不需要自己准备DDL和DML命令了。 最好也分享您尝试过的内容。
写在 postgresql 标准中。 它可能对你有帮助。
select
distinct
first_value(pid) over(w) as pid,
first_value(cid) over(w),
first_value(category) over(w),
first_value(price) over(w),
first_value(created_date) over(w)
from products
window w as (partition by cid,category order by created_date desc)
在 Postgresql 数据库中测试。 它按预期工作。
如果你的MySQL
版本是8.0以上,那么我们可以用windows function来做
create table test_data(
product_id int,
client_id int,
category varchar(10),
price float,
created_date date
);
insert into test_data(product_id,client_id,category,price,created_date) values
(1,1,'A',3.1,'2022-11-01'),
(2,1,'A',3.2,'2022-11-02'),
(3,1,'B',3.3,'2022-11-03'),
(4,1,'B',3.4,'2022-11-04'),
(5,2,'B',3.5,'2022-11-05'),
(6,2,'B',3.6,'2022-11-06'),
(7,2,'A',3.7,'2022-11-07'),
(8,2,'C',3.8,'2022-11-08');
SELECT t.*
FROM
(SELECT *,
row_number() over(PARTITION BY client_id,category order by created_date DESC) as tn from test_data) as t
WHERE t.tn=1
order by t.product_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.