标准值> 10的Mysql查询,连续日期为3小时

问题描述 投票:1回答:3

考虑一个id为id,date datetime,value double的表,我每分钟都有表中的数据。

我正在尝试使用mysql来识别“事件”,其中值> 10连续超过3小时。

当我使用查询时:

select date from table where value > 10;

然后我手动阅读日期连续的地方。

“事件”的示例:

Date             - value
2000/01/01 00:00 - 5
2000/01/01 01:00 - 5
2000/01/01 02:00 - 5
2000/01/01 03:00 - 11
2000/01/01 04:00 - 11
2000/01/01 05:00 - 11
2000/01/01 06:00 - 5
2000/01/01 07:00 - 5
2000/01/01 08:00 - 5
2000/01/01 09:00 - 11
2000/01/01 10:00 - 11
2000/01/01 11:00 - 5

在这种情况下,在03:00和05:00之间有一个“事件”。

mysql sql
3个回答
2
投票

在MySQL中,您可以在检索数据时在SELECT语句中分配变量。此功能有助于解决许多问题,其中“通常”使用窗口函数(MySQL没有)。它也可以帮助你。这是我最终得到的解决方案:

SET @startdate = CAST(NULL AS datetime);
SET @granularity = 60;   /* minutes */
SET @minduration = 180;  /* minutes */
SET @minvalue = 10;

SELECT
  t.Date,
  t.Value
FROM (
  SELECT
    StartDate,
    MAX(Date) AS EndDate
  FROM (
    SELECT
      Date,
      Value,
      CASE
        WHEN Value > @minvalue OR @startdate IS NOT NULL
        THEN IFNULL(@startdate, Date)
      END AS StartDate,
      @startdate := CASE
        WHEN Value > @minvalue
        THEN IFNULL(@startdate, Date)
      END AS s
    FROM (
      SELECT Date, Value FROM YourTable
      UNION ALL
      SELECT MAX(Date) + INTERVAL @granularity MINUTE, @minvalue FROM YourTable
    ) s
    ORDER BY Date
  ) s
  WHERE StartDate IS NOT NULL
  GROUP BY StartDate
) s
  INNER JOIN YourTable t ON t.Date >= s.StartDate AND t.Date < s.EndDate
WHERE s.EndDate >= s.StartDate + INTERVAL @minduration MINUTE
;

这里使用的四个变量中的三个仅仅是脚本参数,并且只有一个@startdate实际上在查询中分配和检查。

基本上,查询迭代行,标记值大于特定最小值(@minvalue)的行,最终生成一个时间范围列表,在此期间值与条件匹配。实际上,为了正确地计算结束边界,紧跟在匹配组的组之后的非匹配行也包括在各个组中。因此,在原始数据集中添加了一个额外的行,其中Date是根据最新的Date加上表中指定的时间戳@granularity来计算的,而Value只是@minvalue

获得后,范围列表将连接回原始表,以检索落在范围边界之间的详细信息行,这些范围不够长(由@minduration指定)在此过程中被过滤掉。

如果您运行此解决方案on SQL Fiddle,您将看到以下输出:

DATE                            VALUE
------------------------------  -----
January, 01 2000 03:00:00-0800  11
January, 01 2000 04:00:00-0800  11
January, 01 2000 05:00:00-0800  11

据我所知,这是你所期望的。


0
投票
select count(*) from table where DATE_SUB(CURDATE(),INTERVAL 3 HOUR) < `date`

select count(*) from table where DATE_SUB(CURDATE(),INTERVAL 3 HOUR) < `date` AND `value` > 10

然后比较结果,如果不相同,则不连续。


0
投票

胡乱猜测:

select * from 
    (select event, MAX(date) as date from table where value > 10 group by event) maxs
inner join 
    (select event, MIN(date) as date from table where value > 10 group by event) mins
on maxs.event = mins.event
where (time_to_sec(timediff(maxes.date, mins.date)) / 3600) > 3
© www.soinside.com 2019 - 2024. All rights reserved.