【问题标题】:How to count boolean transitions on MYSQL?如何计算 MYSQL 上的布尔转换?
【发布时间】:2017-05-09 10:35:35
【问题描述】:

如果我有这张桌子:

Timestamp            | Raining
---------------------|----------
2016-11-01 8:52:43   | 1
2016-11-01 10:47:39  | 1
2016-11-01 15:19:52  | 0
2016-11-01 15:57:32  | 0
2016-11-03 7:45:01   | 1
2016-11-03 8:10:12   | 0
2016-11-03 9:51:36   | 1
2016-11-03 14:28:42  | 1
2016-11-03 15:14:30  | 0
2016-11-03 18:08:26  | 0

0 = not raining1 = raining 在哪里

我如何计算下雨停了多少次,开始下雨了多少次?

我正在使用 MySQL。

【问题讨论】:

  • 请提供想要的结果。

标签: mysql select count boolean transitions


【解决方案1】:

您可以使用会话变量找到最后一个值,找到与当前值的差异并取对应的count

--stopped =>  1 -> 0, diff = -1
--started =>  0 -> 1, diff = 1

select count(case when diff > 0 then 1 end) rain_started,
 count(case when diff < 0 then 1 end) rain_stopped
from 
(select raining, raining - @lr diff, @lr := raining lr
from (select * from my_table order by timestamp) t,
 (select @lr := null) x
) x;

SQLFiddle

【讨论】:

  • 谢谢@Gurwinder-Singh 先生。但它不起作用。我认为在第一个“from”子句之后缺少一些东西。
【解决方案2】:

我不知道 MySQL 是否会处理这个问题,我猜这不会太高效,但它似乎在 SQLServer 中完成了这项工作。根据需要更改表/列名称。

select RainingNow, Count(*) ChangeCount
FROM (
    Select t1.TheTime, t1.Raining RainingNow, nr.Raining RainingNext
    FROM RainTable t1
    INNER JOIN (
        select TheTime ThisTime, (select min(TheTime) from RainTable where TheTime > rt.TheTime) NextTime
        from RainTable rt
        ) n on t1.TheTime = n.ThisTime
    INNER JOIN RainTable nr on n.NextTime = nr.TheTime
    where t1.Raining <> nr.Raining
) as T2
Group By RainingNow

【讨论】:

    【解决方案3】:
    Select count(*)  from table_name where raining=1;
    

    假设下雨是列名

    【讨论】:

    • 如果不试试raining='1'
    • 你的选择让我一直在下雨。我只想计算从 0 变为 1 或从 1 变为 0 的次数。无论如何,谢谢。
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2010-12-16
    相关资源
    最近更新 更多