SQL 语句能实现这样的查询吗?对每个 ID 取最后的 2 条记录。

hiflower 2003-11-18 05:12:14
SQL 语句能实现这样的查询吗?对每个 ID 取最后的 2 条记录。
如 Data 表:
ID TheTime Data2
1 00:00:01 11
1 00:00:02 12
1 00:00:03 13
1 00:00:04 13
2 00:00:01 9
2 00:00:02 8
2 00:00:03 12
3 00:00:04 10
3 00:00:05 10
3 00:00:06 11
要得到:
ID TheTime Data2
1 00:00:03 13
1 00:00:04 13
2 00:00:02 8
2 00:00:03 12
3 00:00:05 10
3 00:00:06 11
...全文
77 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
hiflower 2003-11-18
  • 打赏
  • 举报
回复
谢谢各位,我就是要对每个 ID 取时间最大的 2 条记录,看看诸位提供的答案好象是行的,我明天试过后就结贴。
我用的是 SQL SERVER 2000
txlicenhe 2003-11-18
  • 打赏
  • 举报
回复
select * from table a where Thetime in (select top 2 Thetime from table
where id=a.id order by Thetime desc)

eddiezhuo 2003-11-18
  • 打赏
  • 举报
回复
up
yown 2003-11-18
  • 打赏
  • 举报
回复
Select * from table a where TheTime in (select top 2 TheTime from table
where id=a.id order by TheTime desc)
shuiniu 2003-11-18
  • 打赏
  • 举报
回复
--建表
create table data
(
id int,
thetime datetime,
data2 int
)

--测试数据
insert data values(1,'00:00:01',11)
insert data values(1,'00:00:02',12)
insert data values(1,'00:00:03',13)
insert data values(1,'00:00:04',13)
insert data values(2,'00:00:01',9)
insert data values(2,'00:00:02',8)
insert data values(2,'00:00:03',12)
insert data values(3,'00:00:04',10)
insert data values(3,'00:00:05',10)
insert data values(3,'00:00:06',11)

--实现
select a.id,a.thetime,a.data2
from data a join data b
on a.id = b.id
group by a.id,a.thetime,a.data2
having count(case when a.thetime <= b.thetime then 1 else null end) < = 2 --可动态修改


--你可以以动态的修改: n <= n 来获得
--对每个 ID 取最后的 n 条记录。

zgdhj95 2003-11-18
  • 打赏
  • 举报
回复
select * from table a where Thetime in (select top 2 Thetime from table
where id=a.id order by Thetime desc)
愉快的登山者 2003-11-18
  • 打赏
  • 举报
回复
select * from Data A
where Thetime in (select top 2 Thetime from Data order by Thetime desc
where id=A.id)
zjcxc 元老 2003-11-18
  • 打赏
  • 举报
回复
--看结果,楼主好像是要得到最大的两条,应该用:

select * from table a where Thetime in (select top 2 Thetime from table
where id=a.id order by Thetime desc)
愉快的登山者 2003-11-18
  • 打赏
  • 举报
回复
select * from Data A
where Thetime in (select top 2 Thetime from Data desc
where id=A.id)
zjcxc 元老 2003-11-18
  • 打赏
  • 举报
回复
select * from table a where Thetime in (select top 2 Thetime from table
where id=a.id)
happydreamer 2003-11-18
  • 打赏
  • 举报
回复
select * from table a where Thetime in (select top 2 Thetime from table
where id=a.id)

34,591

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧