我是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 |
---------------------------------------------------
正如您所看到的,RobotShortestPath列中有重复的值,但它们很重要。每个数字代表一个特定的任务。如果数字连续重复(例如:1456),则表示机器人正在执行该任务,当数字发生变化时(例如:1234),这意味着它已切换到另一个任务。并且如果先前的数字(例如:1456)再次出现,则还意味着机器人在完成早期任务(1234)之后正在执行新任务(1456)。
因此,我陷入困境的是我无法完成任务。我从COUNT,GROUP BY这些最低限度的知识中使用了一些东西,但似乎没什么用。
这里执行的任务数量实际上是5,但无论我做什么,我只得到3个结果。
答案 0 :(得分:3)
SET @last_task = 0;
SELECT SUM(new_task) AS tasks_performed
FROM (
SELECT
IF(@last_task = RobotShortestPath, 0, 1) AS new_task,
@last_task := RobotShortestPath
FROM table
ORDER BY ??
) AS tmp
多个表的更新
从数据库结构normailization视图,你最好用一个表,并有一个字段标识什么列是什么机器人,如果由于某种原因不可能,你可以通过联合表得到它:
SET @last_task = 0;
SELECT robot_id, SUM(new_task) AS tasks_performed
FROM (
SELECT
IF(@last_task = RobotShortestPath, 0, 1) AS new_task,
@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
答案 1 :(得分:0)
据我了解,您需要跟踪RobotShortestPath
何时更改为其他值。为此,您可以使用trigger,如下所示:
delimiter |
CREATE TRIGGER track AFTER UPDATE ON yourtable
FOR EACH ROW BEGIN
IF NEW.RobotShortestPath != OLD.RobotShortestPath THEN
UPDATE tracktable SET counter=counter+1 WHERE tracker=1;
END IF;
END;
|
delimeter ;
答案 2 :(得分:0)
set @n:=0, @i:=0;
select max(sno) from
(
select @n:=case when @i=RobotShortestPath then @n else @n+1 end as sno,
@i:=RobotShortestPath as dno
from table
) as t;
答案 3 :(得分:0)
尝试以下查询:
SET @cnt = 0, @r = -1;
SELECT IF(armed <> @r, @cnt:= @cnt + 1, 0), @r:= RobotShortestPath, @cnt FROM table;
SELECT @cnt AS count;