1

我正在使用 SQL Server 2008。

下面是一个示例记录集。

我想在每次更改时查询一次“值”。例如,我想要第 1、9、14、26、28、37 和 50 行。

我曾尝试使用 SELECT DISTINCT,但这不起作用,因为“值”列具有重复值(即第 1 行和第 14 行)。

我一直在寻找一段时间,但没有找到解决方案。如果你有,请告诉我!谢谢!

Row Value   Time Stamp
1   1916    2013-10-01 00:05:00
2   1916    2013-10-01 00:06:00
3   1916    2013-10-01 00:07:00
4   1916    2013-10-01 00:08:00
5   1916    2013-10-01 00:09:00
6   1916    2013-10-01 00:18:00
7   1916    2013-10-01 00:21:00
8   1916    2013-10-01 00:22:00
9   2272    2013-10-01 00:36:00
10  2272    2013-10-01 00:37:00
11  2272    2013-10-01 00:40:00
12  2272    2013-10-01 00:41:00
13  2272    2013-10-01 00:42:00
14  1916    2013-10-01 00:43:00
15  1916    2013-10-01 00:55:00
16  1916    2013-10-01 00:56:00
17  1916    2013-10-01 00:58:00
18  1916    2013-10-01 00:59:00
19  1916    2013-10-01 01:02:00
20  1916    2013-10-01 01:03:00
21  1916    2013-10-01 01:05:00
22  1916    2013-10-01 01:06:00
23  1916    2013-10-01 01:07:00
24  1916    2013-10-01 01:08:00
25  1916    2013-10-01 01:09:00
26  1860    2013-10-01 01:20:00
27  1860    2013-10-01 01:21:00
28  2272    2013-10-01 01:22:00
29  2272    2013-10-01 01:23:00
30  2272    2013-10-01 01:24:00
31  2272    2013-10-01 01:25:00
32  2272    2013-10-01 01:26:00
33  2272    2013-10-01 01:27:00
34  2272    2013-10-01 01:28:00
35  2272    2013-10-01 01:29:00
36  2272    2013-10-01 01:30:00
37  1917    2013-10-01 01:31:00
38  1917    2013-10-01 01:36:00
39  1917    2013-10-01 01:37:00
40  1917    2013-10-01 01:39:00
41  1917    2013-10-01 01:42:00
42  1917    2013-10-01 01:43:00
43  1917    2013-10-01 01:47:00
44  1917    2013-10-01 01:48:00
45  1917    2013-10-01 01:49:00
46  1917    2013-10-01 01:54:00
47  1917    2013-10-01 01:55:00
48  1917    2013-10-01 01:56:00
49  1917    2013-10-01 02:01:00
50  1860    2013-10-01 02:02:00
51  1860    2013-10-01 02:03:00
52  1860    2013-10-01 02:05:00
53  1860    2013-10-01 02:07:00
54  1860    2013-10-01 02:08:00
4

2 回答 2

4

在最新版本的 SQL Server 中,您可以使用该lag()函数。假设你有一个旧版本,你可以使用一个相关的子查询来代替:

select Value, TimeStamp
from (select t1.*,
             (select top 1 value
              from t t2
              where t2.timestamp < t.timestamp
              order by timestamp desc
             ) as prevvalue
      from t t1
     ) t1
where prevvalue is null or prevvalue <> value;
于 2013-11-07T21:11:22.267 回答
0

我显然还不能发表评论......

where t2.timestamp < t.timestamp 

应该

where t2.timestamp < t1.timestamp

以上使用公用表表达式

;with cte as (select t1.*,
             (select top 1 value
              from table1 t2
              where t2.timestamp < t1.timestamp
              order by timestamp desc
             ) as prevvalue
      from table1 t1
     ) 
select Value, TimeStamp
from cte
where prevvalue is null 
or prevvalue <> value
于 2013-11-07T23:37:37.970 回答