sql语句 查出某字段的最后一条记录

影月蓝魔 2012-09-29 09:45:57
在一张表上有多个重复的数据,怎么做才能找出不同数据的最后一条记录。
ID stu_id endDate
1 10 2011/10/10
2 10 2011/10/11
3 11 2011/10/12
4 11 2011/10/13
5 12 2011/10/14
6 12 2011/10/15
就是找出
stu_id=10的最后时间
stu_id=11的最后时间
......
...全文
419 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
發糞塗牆 2012-10-02
  • 打赏
  • 举报
回复
WITH test (ID, stu_id ,endDate)
AS (
SELECT 1, 10, '2011/10/10'
UNION ALL
select 2, 10, '2011/10/11'
UNION ALL
select 3, 11, '2011/10/12'
UNION ALL
select 4 ,11, '2011/10/13'
UNION ALL
select 5 ,12, '2011/10/14'
UNION ALL
select 6 ,12, '2011/10/15')
SELECT * FROM test a
WHERE EXISTS(SELECT 1 FROM (
SELECT stu_id,MAX(enddate)enddate FROM test GROUP BY stu_id) b WHERE a.stu_id=b.stu_id AND a.enddate=b.enddate)

/*
ID stu_id endDate
----------- ----------- ----------
2 10 2011/10/11
4 11 2011/10/13
6 12 2011/10/15

(3 行受影响)
*/
七不语v 2012-09-29
  • 打赏
  • 举报
回复
SELECT stu_id ,MAX(enDate) AS enDate FROM tableName GROUP BY stu_id

上句忘加逗号。
七不语v 2012-09-29
  • 打赏
  • 举报
回复
SELECT stu_id MAX(enDate) FROM tableName GROUP BY stu_id
jianguangguo 2012-09-29
  • 打赏
  • 举报
回复
select * into 新表(可以随意命名,自动根据旧表生成新表表结构) from 旧表 where id in (select id from 旧表 where enddate in(select max(enddate) from tb group by (stu_id)) )
yibey 2012-09-29
  • 打赏
  • 举报
回复
你试验过楼上的各种代码么
影月蓝魔 2012-09-29
  • 打赏
  • 举报
回复
感谢楼上的回答,但是我要的结果是
ID stu_id enDate
2 10 2011/10/11
4 11 2011/10/13
6 12 2011/10/15
不仅要取出,还要在一张表上的,楼上的都是一条一条的数据。
以学习为目的 2012-09-29
  • 打赏
  • 举报
回复

--sql 2005以上版本
select * from
(select *,rn=row_number()over(partition by stu_id order by enddate)from tb)a
where rn=2
--sql 2000
--1、
select * from tb a
where not exists(select 1 from tb where stu_id=a.stu_id and endDate>a.endDate)
--2、
select * from tb where enddate in(select max(enddate) from tb group by (stu_id))

以学习为目的 2012-09-29
  • 打赏
  • 举报
回复
select * from tb where enddate in(select max(enddate) from tb group by (stu_id))
快溜 2012-09-29
  • 打赏
  • 举报
回复
select * from tb a
where not exists(select 1 from tb where stu_id=a.stu_id and endDate>a.endDate)

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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