1

假设我有下表:

data_point (creation_datetime DATETIME PRIMARY KEY, 
            data_point INTEGER);

我正在寻找一个 SQL 查询,它不仅会告诉我最新条目的 data_point 值是否为 X,而且它之后有多少连续行也有 X 作为值。

例如,假设以下数据:

creation_datetime       data_point
2012-10-31 12:00:00     0
2012-10-31 11:55:00     0
2012-10-31 11:50:00     0
2012-10-31 11:45:00     2
2012-10-31 11:40:00     0

如果我有 X=0,我想要回到这里的数字是 3,因为最近的值匹配 X,接下来的 2 行也匹配它。

我没有任何 ID 列或任何东西。如果需要,我可以添加一个,但我想避免它。

4

3 回答 3

2
select count(*) as num
from data_point
where creation_datetime > (
  select max(creation_datetime)
  from data_point
  where data_point <> 0
)

计算最后一条不是您想要的值的记录之后的记录数。

于 2012-10-31T21:21:49.243 回答
2
SELECT max(creation_datetime), data_point, count(*)
FROM  data_points, (
  SELECT max(creation_datetime) time_of_last_data_point 
  FROM data_points 
  WHERE data_point <> (
    SELECT data_point FROM data_points ORDER BY creation_datetime DESC LIMIT 1
  )
) 
WHERE 
  creation_datetime > time_of_last_data_point
GROUP BY 
  data_point

解释:

  • 嵌套的 select 语句将找到条目2012-10-31 11:45:00 | 2
  • 外部选择仅限于在 之后添加的记录2012-10-31 11:45:00

注意:您必须稍微清理一下才能将其与其他数据库一起使用。

于 2012-10-31T23:41:56.207 回答
1
declare @data_point table (creation_datetime DATETIME PRIMARY KEY, data_point INTEGER)
insert @data_point
      select '2012-10-31 12:00:00',     0
union select '2012-10-31 11:55:00',     0
union select '2012-10-31 11:50:00',     0
union select '2012-10-31 11:45:00',     2
union select '2012-10-31 11:40:00',     0

declare @x integer
set @x = 0

--solution 1
select COUNT(*) 
from @data_point 
where data_point = @x
and creation_datetime > 
(
    select max(creation_datetime)
    from @data_point 
    where data_point != @x 
)

--solution 2
select COUNT(*) 
from @data_point a
where data_point = @x
and not exists
(
    select top 1 1
    from @data_point b
    where data_point != @x 
    and a.creation_datetime < b.creation_datetime
)
于 2012-10-31T21:20:02.723 回答