postgrel實現相同id數據合併

需求如下:
有表結構如下

id name create_time
1 王二狗 2018-12-25 11:22:00
2 張三瘋 2018-12-25 11:23:00
2 李四蛋 2018-12-25 12:23:00

現在需要根據時間排序後將相同id的字段合併起來並取出其中最大的時間,sql寫法如下:
select id max(t.create_time) , string_agg(name, ’ | ') as name, string_agg(cast( t.create_time as text), ’ | ') as name, ( select * from table_test order by create_time desc) as t group by t.id

查出來數據結果如下:

id max name create_time
2 2018-12-25 12:23:00 張三瘋 | 李四蛋 2018-12-25 12:23:00| 2018-12-25 11:23:00
1 2018-12-25 11:22:00 王二狗 2018-12-25 11:22:00
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章