特定值的序列MySql表

时间:2016-11-18 13:09:54

标签: mysql

我正在尝试计算具有值的连续行数。举一个简单的例子,考虑抛出2个骰子,得到值1-12。我想获得具有相同总数的连续行的最高序列的值的表。这是表定义,填充表的存储过程和执行存储过程的命令:

\s

如果选择总计列表(CREATE TABLE `Dice_throws` ( `idx` int(11) NOT NULL AUTO_INCREMENT, `Dice1` tinyint(1) DEFAULT NULL, `Dice2` tinyint(1) DEFAULT NULL, PRIMARY KEY (`idx`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1; --------------------------------- DELIMITER $$ CREATE PROCEDURE InsertDiceThrows(IN NumRows INT) BEGIN DECLARE i INT; SET i = RAND(12345); /* use the same seed */ SET i = 1; START TRANSACTION; WHILE i <= NumRows DO INSERT INTO Dice_throws(Dice1, Dice2) VALUES (CEIL(RAND() * 6), CEIL(RAND() * 6)); SET i = i + 1; END WHILE; COMMIT; END$$ DELIMITER ; ----------------------------- call InsertDiceThrows(2000); ),那么我将获得2000行,例如SELECT Dice1, Dice2, Dice1+Dice2 FROM Dice_throws order by idx;等等。 最后,我想要一个像这样的表:

2,5,12,6,7,4,8,8,8,5,11,6,6,

因此,这表明总数为4的连续行上的最大序列为3,连续8行,其中总数为6等。所以我想找到每个可能结果具有相同总数的最高序列卷。 我显然可以在PHP中完成它(我已经使它与PHP一起工作)只需选择总数然后循环遍历结果集但我想知道是否有一些很好的方法在SQL中完成它。 感谢任何提示或解决方案。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

CREATE TABLE test (rid int auto_increment PRIMARY KEY, v int not null);
INSERT test (v) VALUES (2),(2),(3),(3),(3),(2),(4),(4),(4),(4),(4),(4),(2),(2),(2),(2),(1);

SELECT * FROM test;

CREATE TABLE chunks (cid int auto_increment PRIMARY KEY, v int not null, c int not null, s int not null);
INSERT chunks(cid,v,c,s)
SELECT null,t1.v,t1.rid AS c, 0
FROM test t1
LEFT JOIN test t2 ON t1.rid=t2.rid-1 AND t1.v=t2.v
WHERE t2.rid IS NULL;

UPDATE chunks c1 LEFT JOIN chunks c2 ON c1.cid=c2.cid+1
SET c1.s=CASE WHEN c2.c IS NULL THEN 1 ELSE c2.c+1 END;
SELECT * FROM chunks;

SELECT v.v,MAX(v.cnt) AS max_cnt
FROM (
  SELECT c.c, MIN(t1.v) AS v, COUNT(*) AS cnt
  FROM test t1
  INNER JOIN chunks c
  ON t1.rid between c.s and c.c
  GROUP BY c.c) v
GROUP BY v.v;