t_zhb表结构如下:
task_id type item_id cnt
1 2 1 200
2 2 1 400
1 2 2 500
2 2 2 300
现在想要把type和item_id都相同的记录合并为一行,合并后如下所示:
type item_id cnt
2 1 200,400
2 2 500,300
用GROUP_CONCAT实现
SELECT type, item_id, GROUP_CONCAT(cnt SEPARATOR ',') cnt
FROM t_zhb
GROUP BY type, item_id
想要计算新表中cnt前后两个值的差值的绝对值,并按其绝对值从大到小排列
SELECT type, item_id,
cast(substring_index(cnt,',',1) as Decimal(24))-cast(substring_index(cnt,',',-1) as Decimal(24)) as 差值
from t
order by 差值 desc
转化为Decimal(24)是因为cnt值太大超过integer的话,就要用Decimal,否则用integer就可以。