我是MySQL的新手,我需要你的帮助.我有一张包含类似数据的表格
--------------------------------------------------- |RobotPosX|RobotPosY|RobotPosDir|RobotShortestPath| --------------------------------------------------- |0.1 | 0.2 | 15 | 1456 | |0.2 | 0.3 | 30 | 1456 | |0.54 | 0.67 | 15 | 1456 | |0.68 | 0.98 | 22 | 1234 | |0.36 | 0.65 | 45 | 1234 | |0.65 | 0.57 | 68 | 1456 | |0.65 | 0.57 | 68 | 2556 | |0.79 | 0.86 | 90 | 1456 | ---------------------------------------------------
@H_301_8@正如您所看到的,RobotShortestPath列中有重复的值,但它们很重要.每个数字代表一个特定的任务.如果数字连续重复(例如:1456),则表示机器人正在执行该任务,当数字发生变化时(例如:1234),这意味着它已切换到另一个任务.并且如果先前的数字(例如:1456)再次出现,则还意味着机器人在完成早期任务(1234)之后正在执行新任务(1456).
因此,我陷入困境的是我无法完成任务.我从COUNT,GROUP BY这些最低限度的知识中使用了一些东西,但似乎没什么用.
实际上执行的任务数量实际上是5,但无论我做什么,我只得到3个结果.
最佳答案
SET @last_task = 0; SELECT SUM(new_task) AS tasks_performed FROM ( SELECT IF(@last_task = RobotShortestPath,1) AS new_task,@last_task := RobotShortestPath FROM table ORDER BY ?? ) AS tmp
@H_301_8@更新多个表
从数据库结构normailization视图,你最好用一个表,并有一个字段标识什么列是什么机器人,如果由于某种原因不可能,你可以通过联合表得到它:SET @last_task = 0; SELECT robot_id,SUM(new_task) AS tasks_performed FROM ( SELECT IF(@last_task = RobotShortestPath,@last_task := RobotShortestPath FROM ( SELECT 1 AS robot_id,robot_log_1.* FROM robot_log_1 UNION SELECT 2,robot_log_2.* FROM robot_log_2 UNION SELECT 3,robot_log_3.* FROM robot_log_3 UNION SELECT 4,robot_log_4.* FROM robot_log_4 UNION SELECT 5,robot_log_5.* FROM robot_log_5 ) as robot_log ORDER BY robot_id,robot_log_id ) AS robot_log_history GROUP BY robot_id ORDER BY tasks_performed DESC
@H_301_8@