如何查询多个子记录集中的不同值

时间:2013-11-07 21:07:29

标签: sql sql-server sql-server-2008

我正在使用SQL Server 2008。

下面是一个示例记录集。

我想在每次更改时查询“值”。例如,我想要排#1,9,14,26,28,37& 50。

我尝试过使用SELECT DISTINCT,但这不起作用,因为“Value”列有重复值(即第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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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