MySQL 按顺序计算变化
MySQL count changes in sequence
我正在尝试找到一种方法来计算有序列表中值更改的次数。给定一个序列,例如 A, B, A, A, B, C, C
,将有 4 个变化,忽略第一个。
我需要的是在 ORDER BY y
之后应用 COUNT(GROUP BY x)
命令之类的东西,但这不是有效的语法。有没有一种简单的方法可以在纯 MySQL 中完成此操作,还是我最好使用 Python 进行迭代?
table 将按日期字段排序。例如:
+------------+-------+
| Date | Value |
+------------+-------+
| 2015-09-01 | A |
| 2015-09-02 | B | (change)
| 2015-09-03 | A | (change)
| 2015-09-05 | A |
| 2015-09-06 | B | (change)
| 2015-09-07 | C | (change)
| 2015-09-08 | C |
+------------+-------+
计划
- order by Date
- calculate lag variable over the ordering
- calculate changes ( comparing to lag variable )
- take max(changes) and subtract one for ( for the first transition.. )
查询
set @chgs := 0;
set @lag := null;
select max(chgs) - 1 as num_changes
from
(
select `Date`, `Value`,
@chgs := if(@lag = `Value`, @chgs,
if(@lag := `Value`, @chgs + 1, @chgs + 1)) as chgs
from sequence
order by `Date`
) calc
;
输出
+-------------+
| num_changes |
+-------------+
| 4 |
+-------------+
我正在尝试找到一种方法来计算有序列表中值更改的次数。给定一个序列,例如 A, B, A, A, B, C, C
,将有 4 个变化,忽略第一个。
我需要的是在 ORDER BY y
之后应用 COUNT(GROUP BY x)
命令之类的东西,但这不是有效的语法。有没有一种简单的方法可以在纯 MySQL 中完成此操作,还是我最好使用 Python 进行迭代?
table 将按日期字段排序。例如:
+------------+-------+
| Date | Value |
+------------+-------+
| 2015-09-01 | A |
| 2015-09-02 | B | (change)
| 2015-09-03 | A | (change)
| 2015-09-05 | A |
| 2015-09-06 | B | (change)
| 2015-09-07 | C | (change)
| 2015-09-08 | C |
+------------+-------+
计划
- order by Date
- calculate lag variable over the ordering
- calculate changes ( comparing to lag variable )
- take max(changes) and subtract one for ( for the first transition.. )
查询
set @chgs := 0;
set @lag := null;
select max(chgs) - 1 as num_changes
from
(
select `Date`, `Value`,
@chgs := if(@lag = `Value`, @chgs,
if(@lag := `Value`, @chgs + 1, @chgs + 1)) as chgs
from sequence
order by `Date`
) calc
;
输出
+-------------+
| num_changes |
+-------------+
| 4 |
+-------------+