gpt4 book ai didi

mysql - SQL - 按列 1 分组,按列 2 排序

转载 作者:行者123 更新时间:2023-11-29 15:20:49 25 4
gpt4 key购买 nike

这是我的情况,我有两个表,分别名为 peoplecontacts

id name
1 dev one
2 dev two
3 dev three
4 dev five
5 dev four
id  person_id code_name updated_at
1 1 base1 2019-12-18 00:00:01
2 3 base2 2019-12-18 00:00:02
3 2 home 2019-12-18 00:00:03
4 2 home2 2019-12-18 00:00:04
5 3 work 2019-12-18 00:00:05
6 4 work 2019-12-18 00:00:06
7 5 base 2019-12-18 00:00:07
8 4 base2 2019-12-18 00:00:08
9 2 base 2019-12-18 00:00:09
10 5 work 2019-12-18 00:00:10

我正在尝试从联系人中获取结果,其中联系人按最新的updated_at排序并按person_id分组(注意:不完全是sql“分组依据”),看起来类似于以下结果。

id  person_id code_name updated_at
10 5 work 2019-12-18 00:00:10
7 5 base 2019-12-18 00:00:07
9 2 base 2019-12-18 00:00:09
4 2 home2 2019-12-18 00:00:04
3 2 home 2019-12-18 00:00:03
8 4 base2 2019-12-18 00:00:08
6 4 work 2019-12-18 00:00:06
5 3 work 2019-12-18 00:00:05
2 3 base2 2019-12-18 00:00:02
1 1 base1 2019-12-18 00:00:01

目前,我正在按 person_id descupdated_at desc 对联系人表进行排序,结果有点接近我的预期,但并不完全正确。

执行ORDER BY person_id DESC, Updated_at DESC时查看结果 https://monosnap.com/file/xN0cuZAu2x2df4Q5qNDksKq5P3sEjUid => 1 的联系应该位于结果集的顶部,因为它是所有结果集中最新更新的。

注意:PostgreSQL 是我在这种情况下的第一个用例,但很高兴知道 MySQL 是否有任何差异。

最佳答案

我在 PostgreSQL 9.3 中尝试了以下操作。

数据样本:

create table contact
(
id int,
person_id int,
code_name varchar(20),
updated_at timestamp
);

INSERT INTO contact VALUES
(1,1,'base1','2019-12-18 00:00:01'),
(2,3,'base2','2019-12-18 00:00:02'),
(3,2,'home','2019-12-18 00:00:03'),
(4,2,'home2','2019-12-18 00:00:04'),
(5,3,'work','2019-12-18 00:00:05'),
(6,4,'work','2019-12-18 00:00:06'),
(7,5,'base','2019-12-18 00:00:07'),
(8,4,'base2','2019-12-18 00:00:08'),
(9,2,'base','2019-12-18 00:00:09'),
(10,5,'work','2019-12-18 00:00:10');

查询:

DROP TABLE IF EXISTS TEMP_Stage_Table;

SELECT string_agg(id::text,',' order by updated_at desc) id,
person_id,
string_agg(code_name,',' order by updated_at desc) code_name,
string_agg(updated_at::text,',' order by updated_at desc) updated_at INTO TEMP_Stage_Table
FROM contact
GROUP BY person_id
ORDER BY MAX(updated_at) DESC;

SELECT regexp_split_to_table(t.id, E',') AS id,
t.person_id,
regexp_split_to_table(t.code_name, E',') AS code_name,
regexp_split_to_table(t.updated_at, E',') AS updated_at
FROM TEMP_Stage_Table t;

输出:

enter image description here

关于mysql - SQL - 按列 1 分组,按列 2 排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59385588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com