假设我有一个带有ID标识列的表,一些数据和一个日期戳。像这样:
1 data 5/1/2013 12:30
2 data 5/2/2013 15:32
3 data 5/2/2013 16:45
4 data 5/3/2013 9:32
5 data 5/5/2013 8:21
6 data 5/4/2013 9:36
7 data 5/6/2013 11:42
如何编写一个查询,向我显示一个时间戳为5/4的记录?该表有数百万条记录。我做了一些搜索,但我不知道该怎么称呼我正在寻找的东西。 :/
答案 0 :(得分:7)
declare @t table(id int, bla char(4), timestamp datetime)
insert @t values
(1,'data','5/1/2013 12:30'),
(2,'data','5/2/2013 15:32'),
(3,'data','5/2/2013 16:45'),
(4,'data','5/3/2013 9:32'),
(5,'data','5/5/2013 8:21'),
(6,'data','5/4/2013 9:36'),
(7,'data','5/6/2013 11:42')
select timestamp
from
(
select rn1 = row_number() over (order by id),
rn2 = row_number() over (order by timestamp), timestamp
from @t
) a
where rn1 not in (rn2, rn2-1)
答案 1 :(得分:0)
在2008年r2,这将是一种方式
DECLARE @Table AS TABLE
(id INT , ladate DATETIME)
INSERT INTO @Table VALUES (1, '2013-05-01')
INSERT INTO @Table VALUES (2, '2013-05-02')
INSERT INTO @Table VALUES (3, '2013-05-03')
INSERT INTO @Table VALUES (4, '2013-05-05')
INSERT INTO @Table VALUES (5, '2013-05-04')
INSERT INTO @Table VALUES (6, '2013-05-06')
INSERT INTO @Table VALUES (7, '2013-05-07')
INSERT INTO @Table VALUES (8, '2013-05-08')
- 我在排序顺序中添加了记录,但如果不是只是确保在查询中排序
SELECT t2.ladate FROM @Table T1
INNER JOIN @Table T2 ON T1.Id = T2.Id + 1
INNER JOIN @Table t3 ON t2.id = t3.id + 1
WHERE t3.ladate < t2.ladate AND t2.ladate > t1.ladate
- 我假设你的Id都在那里,1,2,3,4,5 ....没有丢失......如果有rownumbers缺失,你可以使用row_number()