假设我有下表:
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列或任何内容。如果需要,我可以添加一个,但我想避免它。
答案 0 :(得分:2)
select count(*) as num
from data_point
where creation_datetime > (
select max(creation_datetime)
from data_point
where data_point <> 0
)
计算最后一条记录之后不是所需值的记录数。
答案 1 :(得分: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
说明:
2012-10-31 11:45:00 | 2
。2012-10-31 11:45:00
之后添加的记录。注意:您必须将其清理一下才能与其他数据库一起使用。
答案 2 :(得分: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
)