我已经阅读了几个关于计算连续行的类似问题,但没有一个给我一个明确的答案。我希望有人可以帮我解决一下我的问题。我有以下表格数据:
ID TEST_VALUES
1 A
2 B
3 C
4 C
5 C
6 C
7 A
8 D
9 D
10 D
11 B
12 C
13 C
14 C
15 C
现在我想在ID范围内找到具有相同值的三个连续行是1到10,例如当ID范围是1到10时,有'C'连续出现超过三次。 (注意:这个问题与ID无关,列ID只是我查询的条件,例如ID> 1和ID< 10)
答案 0 :(得分:0)
SELECT
GROUP_CONCAT(`TEST_VALUES` ORDER BY `id` ASC) AS g
FROM
`tbl`
WHERE
`ID` >=1 AND `ID` <= 10
HAVING
g LIKE '%C,C,C,C%'
按GROUP_CONCAT()
订购id
可确保结果是连续的。 HAVING
子句仅提取包含至少四个C序列实例的行。
答案 1 :(得分:0)
你可以试试这个,
SELECT TEST_VALUES, MAX(cnt) AS maxCount
FROM (
SELECT TEST_VALUES, ID, COUNT(grp) AS cnt
FROM (
SELECT ID, TEST_VALUES, rn - rnByVal AS grp
FROM (
SELECT ID, TEST_VALUES,
@rn := @rn + 1 AS rn,
@rnByVal := IF (@val = TEST_VALUES,
IF (@val := TEST_VALUES, @rnByVal + 1, @rnByVal + 1),
IF (@val := TEST_VALUES, 1, 1)) AS rnByVal
FROM mytable
CROSS JOIN (SELECT @rn := 0, @rnByVal := 0, @val := '') AS vars
ORDER BY ID) AS t
) AS s
GROUP BY TEST_VALUES, grp ) AS u
GROUP BY TEST_VALUES
对于具有相同值(大于1)的连续行的返回最大计数。
答案 2 :(得分:0)
我也想到了一个解决方案,希望能帮助别人
SELECT
TEST_VALUES
FROM(
SELECT
m.TEST_VALUES AS TEST_VALUES,
IF(@b = m.TEST_VALUES, @a := @a +1, @a := 0) AS countNUM,
@b := m.TEST_VALUES
FROM tableName m
JOIN (
SELECT
@a := 0
) AS t
) AS TEMP
WHERE countNUM >= 2
GROUP BY TEST_VALUES
答案 3 :(得分:0)
令人费解但经过测试和运作:
SELECT t1.ID AS t1_id, t1.TEST_VALUES AS t1_values,
(SELECT ID FROM test WHERE test.ID > t1.ID LIMIT 1 ) AS t2_id, (SELECT TEST_VALUES FROM test WHERE test.ID > t1.ID LIMIT 1 ) AS t2_values,
(SELECT ID FROM test WHERE test.ID > (SELECT ID FROM test WHERE test.ID > t1.ID LIMIT 1 ) LIMIT 1 ) AS t3_id, (SELECT TEST_VALUES FROM test WHERE test.ID > (SELECT ID FROM test WHERE test.ID > t1.ID LIMIT 1 ) LIMIT 1 ) AS t3_values,
(SELECT ID FROM test WHERE test.ID > (SELECT ID FROM test WHERE test.ID > (SELECT ID FROM test WHERE test.ID > t1.ID LIMIT 1 ) LIMIT 1 ) LIMIT 1 ) AS t4_id, (SELECT TEST_VALUES FROM test WHERE test.ID > (SELECT ID FROM test WHERE test.ID > (SELECT ID FROM test WHERE test.ID > t1.ID LIMIT 1 ) LIMIT 1 ) LIMIT 1 ) AS t4_values
FROM test AS t1
HAVING (
ID BETWEEN 1 AND 10 AND t2_id BETWEEN 1 AND 10 AND t3_id BETWEEN 1 AND 10 AND t4_id BETWEEN 1 AND 10
AND
t1_values = t2_values AND t2_values = t3_values AND t3_values = t4_values
)
给出了这些结果:
+-------+-----------+-------+-----------+-------+-----------+-------+-----------+
| t1_id | t1_values | t2_id | t2_values | t3_id | t3_values | t4_id | t4_values |
+-------+-----------+-------+-----------+-------+-----------+-------+-----------+
| 3 | C | 4 | C | 5 | C | 6 | C |
+-------+-----------+-------+-----------+-------+-----------+-------+-----------+
1 row in set (0.03 sec)