当前位置:网站首页>分组后返回每组中的最后一条记录 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')
边栏推荐
猜你喜欢

Unable to boot after permanent mounting

go的环境搭建和起步

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

RESTful API介绍

RAID5 and LVM are used in combination

File system and log analysis

Common commands and package management of go language

【ESP8266点焊机】基于 ESP8266 for Arduino

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

Disk management and file system
随机推荐
[award issuance] the results of the first essay solicitation activity in oneos zone were announced
File system and log analysis
[small object velocimeter] only principle, no code
JS - calculate the side length and angle of a right triangle
使用自定义zabbix包(4.0.5版本)安装agent和proxy
Browser local storage
Grid layout
JSP tag 02
MySQL batch modifies the data table code and character set to utf8mb4
LM393 电压比较器及其典型电路介绍
【LVGL(2)】LVGL入门,在CodeBlock上进行模拟以及移植STM32
kubernetes简介和架构及其原理
Responsive page
Animation effect
Flink time stream processing
OpenSSL version upgrade
【LVGL(重要)】样式属性API函数及其参数
自定义zabbix agent rpm包
Customize ZABBIX agent RPM package
Quick start of go language