MySql获取相邻数据代码示例

作者:袖梨 2022-06-29

本篇文章小编给大家分享一下MySql获取相邻数据代码示例,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

因为项目,所以找到了一些资料并且总结了下关于获取相邻数据的方式。

只找到了以下的...

/*获取id值与5相减绝对值最近的数据,如果有绝对值相同的,相邻的数据优先输出*/
/*ABS(X)其实就是获取绝对值,然后的话order by 后面的1代表着根据select关键字
后的第一个字段进行排序。limit 后面的数字代表着你想查询数据的行数*/
SELECT ABS(cid-5),cname FROM company ORDER BY 1 LIMIT 3
/*获取指定id的上一条记录,我这里是以id=5为例的*/
select cid,cname from company order by cid>=5,cid desc limit 1
/*获取指定id的下一条记录,我这里是以id=5为例的*/
SELECT cid,cname from company order by cid<=5,cid asc limit 1

记录一下,以免以后遇到又不会

同表相邻数据比对查询

需求

我们将会比对相邻的数据,其中value是递增的,但也会存在清零的情况。我们的需求是计算当天的分钟递增量。

SQL

语句中需要解释一下参数

** ctc_etl.1_1_1907/sum.out_2021 :表名**** WHERE
item_timestamp > “2021-12-01 00:00:00”
AND item_timestamp < “2021-12-02 00:00:00” 是我自己加的筛选条件**
SELECT b.id,( b.item_value - a.item_value ) AS value,
	b.item_timestamp AS time 
FROM
	(
	SELECT id,item_value,
		@num := @num + 1 AS row_number 
	FROM
		( SELECT @num := 0 ) r,
			ctc_etl.`1_1_1907/sum.out_2021` 
	WHERE
		item_timestamp > "2021-12-01 00:00:00" 
		AND item_timestamp < "2021-12-02 00:00:00" 
	ORDER BY
		id 
	) a,
	(
	SELECT
		id,
		item_value,
		item_timestamp,
		@num2 := @num2 + 1 AS row_number 
	FROM
		( SELECT @num2 := 0 ) r2,
			ctc_etl.`1_1_1907/sum.out_2021` 
	WHERE
		item_timestamp > "2021-12-01 00:00:00" 
		AND item_timestamp < "2021-12-02 00:00:00" 
	ORDER BY
		id 
	) b 
WHERE
	a.row_number + 1 = b.row_number;

解析

目前计算的只是每秒的增加量,其次就是存在负数的情况,也就是清零了后一个数比前一个小就造成了负数

最终SQL

SELECT
	c.id,
	SUM( c.VALUE ) AS value,
	DATE_FORMAT( c.time, "%Y-%m-%d %H:%i:00" ) AS time 
FROM
	(
	SELECT
		b.id,
		(b.item_value - a.item_value ) AS value,
		b.item_timestamp AS time 
	FROM
		(
		SELECT
			id,
			item_value,
			@num := @num + 1 AS row_number 
		FROM
			( SELECT @num := 0 ) r,
			ctc_etl.`1_1_1907/sum.out_2021` 
		WHERE
			item_timestamp > "2021-12-01 00:00:00" 
			AND item_timestamp < "2021-12-02 00:00:00" 
		ORDER BY
			id 
		) a,
		(
		SELECT
			id,
			item_value,
			item_timestamp,
			@num2 := @num2 + 1 AS row_number 
		FROM
			( SELECT @num2 := 0 ) r2,
			ctc_etl.`1_1_1907/sum.out_2021` 
		WHERE
			item_timestamp > "2021-12-01 00:00:00" 
		AND item_timestamp < "2021-12-02 00:00:00" ORDER BY id ) b WHERE a.row_number + 1 = b.row_number ) c WHERE c.VALUE > 0 
GROUP BY
	DATE_FORMAT(
	c.time,
	"%Y-%m-%d %H:%i:00")

相关文章

精彩推荐