在Mysql条目中查找模式

时间:2016-03-31 10:26:30

标签: mysql sql

我需要找到大于特定浮点数的记录数,并找到重复次数最多的数据组。

对于示例,我有以下数据,我需要查找有多少条目的值> 4.

    1.5
    1.7
    4.5
    4.7
    4.8
    1.4
    4.5
    4.9

在上述数据中,大于4的最长连续重复值是4.5,4.7,4.8。

因此,我想要归还的总数应为3.

正如您所看到的那样,4.8之后的模式会中断,因为数字是1.4以上。

有没有办法识别这种模式?

1 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?

SELECT count(*) AS nr, IF(num >4,1,0) AS inRange,
@grpnr := IF (@lastval = @lastval:= IF(num >4,1,0),@grpnr,@grpnr+1 )  AS grpnr,
n.* , GROUP_CONCAT(n.num) AS numbers
FROM mynum n
CROSS JOIN ( SELECT @grpnr:=0, @lastval:=0) AS parameter  
GROUP BY grpnr
ORDER BY id;

<强>示例

MariaDB [who]> SELECT * from mynum;
+----+------+
| id | num  |
+----+------+
|  1 |  1.5 |
|  2 |  1.7 |
|  3 |  4.5 |
|  4 |  4.7 |
|  5 |  4.8 |
|  6 |  1.4 |
|  7 |  4.5 |
|  8 |  4.9 |
+----+------+
8 rows in set (0.00 sec)

MariaDB []> SELECT count(*) AS nr, IF(num >4,1,0) AS inRange,
    -> @grpnr := IF (@lastval = @lastval:= IF(num >4,1,0),@grpnr,@grpnr+1 )  AS grpnr,
    -> n.* , GROUP_CONCAT(n.num) AS numbers
    -> FROM mynum n
    -> CROSS JOIN ( SELECT @grpnr:=0, @lastval:=0) AS parameter
    -> GROUP BY grpnr
    -> ORDER BY id;
+----+---------+-------+----+------+-------------+
| nr | inRange | grpnr | id | num  | numbers     |
+----+---------+-------+----+------+-------------+
|  2 |       0 | 0     |  1 |  1.5 | 1.5,1.7     |
|  3 |       1 | 1     |  3 |  4.5 | 4.5,4.7,4.8 |
|  1 |       0 | 2     |  6 |  1.4 | 1.4         |
|  2 |       1 | 3     |  7 |  4.5 | 4.5,4.9     |
+----+---------+-------+----+------+-------------+
4 rows in set (0.01 sec)

MariaDB []>