当前位置:网站首页>分组后返回每组中的最后一条记录 GROUP_CONCAT用法
分组后返回每组中的最后一条记录 GROUP_CONCAT用法
2022-07-24 05:24:00 【魔舞清华】
group_contat语法
group_concat([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符'])
问题描述
如下表:按name分组后返回每组最后一条数据
Id Name Other_Columns
-------------------------
1 A A_data_1
2 A A_data_2
3 A A_data_3
4 B B_data_1
5 B B_data_2
6 C C_data_1
默认情况下分组:
select * from messages group by name
返回数据(默认返回每组的第一条数据),显然不是我们想要的结果
1 A A_data_1
4 B B_data_1
6 C C_data_1
解决方案
使用MySQL的GROUP_CONCAT和SUBSTRING_INDEX
sql如下:
SELECT `Id`,
`Name`,
SUBSTRING_INDEX(
GROUP_CONCAT(
`Other_Columns`
ORDER BY `Id` DESC
SEPARATOR '||'
),
'||',
1
) Other_Columns
FROM messages
GROUP BY `Name`
查询结果:
3 A A_data_3
5 B B_data_2
6 C C_data_1
实践业务sql(生产使用)
查询库存流水表,按biz_no, biz_type, location_id, sku_id, stock_status分组,
返回 分组后surplus_stock(剩余库存)最新的剩余库存数
SELECT flow.biz_type,
flow.location_id,
flow.consignor_id,
flow.stock_status,
flow.sku_id,
flow.biz_no,
SUM(flow.quantity) AS quantity,
flow.area_id,
flow.u_t,
flow.u_u,
flow.operator,
flow.operate_time,
SUBSTRING_INDEX(GROUP_CONCAT(flow.surplus_stock ORDER BY flow.c_t DESC SEPARATOR '||'), '||', 1) surplus_stock
FROM wms_stock_flow flow
GROUP BY biz_no, biz_type, location_id, sku_id, stock_status,FROM_UNIXTIME(flow.u_t/1000,'%Y-%m-%d %H:%i')
边栏推荐
猜你喜欢

Secondary processing of template data

类的加载器 和 双亲委派机制详解

go语言的快速上手

Solution: exit status 1 and exit status 145 appear when the console uses NVM to control the node version

JMeter distributed pressure measurement

FTP服务与实验

【小型物体测速仪】只有原理,无代码

These 10 kinds of timed tasks have been learned, and you can float directly

Special effects - click the mouse, and a random color of love will appear

ESP32超详细学习记录:NTP同步时间
随机推荐
Solution of forgetting root password in mysql5.7 under Windows
神经网络超参数调整(基于ray包)
LM393 电压比较器及其典型电路介绍
系统安全及应用
Custom MVC 1.0
文件系统与日志分析
sed命令
RAID5 and LVM are used in combination
FTP服务与实验
Visibility:hidden and display:none
Solution: exit status 1 and exit status 145 appear when the console uses NVM to control the node version
利用sshpass批量实现基于key验证
These 10 kinds of timed tasks have been learned, and you can float directly
go的环境搭建和起步
Why can't index be the key of V-for?
类的加载器 和 双亲委派机制详解
General paging 2.0
Grid layout
Difference between PX and EM and REM
Secondary processing of template data