这句SQL该如何写好

prqin 2003-12-12 01:34:17
现在有一张表,数据如下

ID Name Type date

1 XXX A 2003-2-1
2 XXX A 2003-1-1
3 XXX A 2003-1-1
4 XXX B 2003-2-1
5 XXX B 2003-1-1
6 XXX B 2003-1-1
7 XXX C 2003-2-1
8 XXX C 2003-1-1
9 XXX C 2003-1-1


如何才能查询出每个类别从时间上来说最新的一条记录,可以是一个存储过程,比如说上面一张表查询结果应该是1,4,7三条记录




...全文
41 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
zsz0527 2003-12-12
  • 打赏
  • 举报
回复
同意楼上的意见,考虑的细致一点
zjcxc 2003-12-12
  • 打赏
  • 举报
回复
--根据楼主的数据,因为同一个type,日期有重复,所以应该用:

select * from 表 a
where id=(select top 1 id from 表 where type=a.type order by date desc)
prqin 2003-12-12
  • 打赏
  • 举报
回复
采用了zjcxc的办法,完全解决了,谢谢!结帖中。。。。
prqin 2003-12-12
  • 打赏
  • 举报
回复
select type ,max(date) from table group by type 是可以,但是
select type ,max(date),name from table group by type 就不行,说name这个字段没有包含再聚合函数中
zjcxc 2003-12-12
  • 打赏
  • 举报
回复
--看楼主给的数据,应该用我上面的方法,下面是数据测试

--测试数据

declare @t table(ID int,Name varchar(10),Type varchar(1),date datetime)
insert into @t
select 1,'XXX','A','2003-2-1'
union all select 2,'XXX','A','2003-1-1'
union all select 3,'XXX','A','2003-1-1'
union all select 4,'XXX','B','2003-2-1'
union all select 5,'XXX','B','2003-1-1'
union all select 6,'XXX','B','2003-1-1'
union all select 7,'XXX','C','2003-2-1'
union all select 8,'XXX','C','2003-1-1'
union all select 9,'XXX','C','2003-1-1'

--查询
select * from @t a
where id=(select top 1 id from @t where type=a.type order by date desc)

/*--测试结果
ID Name Type date
----------- ---------- ---- -------------------------
1 XXX A 2003-02-01 00:00:00.000
4 XXX B 2003-02-01 00:00:00.000
7 XXX C 2003-02-01 00:00:00.000

(所影响的行数为 3 行)
--*/
victorycyz 2003-12-12
  • 打赏
  • 举报
回复

select a.*
from tablename a join
( select type,max([date]) as mdate
from tablename
group by [type]
) b on a.[type]=b.[type] and a.[date]=b.mdate
zjcxc 2003-12-12
  • 打赏
  • 举报
回复
--如果日期不会重复的话,可以用上面的方法,否则建议用下面的方法:

select * from 表 a where id=(select top 1 id from 表 where a.type=type order by 日期 desc)
LoveSQL 2003-12-12
  • 打赏
  • 举报
回复
或者:
select a.* from tablename a ,(select type ,max(date) as date from table group by type ) b
where a.type=b.type and a.date=b.date
tanxiangfeng 2003-12-12
  • 打赏
  • 举报
回复
select * from tablename a inner join (select type ,max(date) from tablename group by type ) b on a.type=b.type
LoveSQL 2003-12-12
  • 打赏
  • 举报
回复
select * from tablename a where date=(select max(date) from tablename where Type=a.Type)
lynx1111 2003-12-12
  • 打赏
  • 举报
回复
select * from tablename a where date=(select max(date) from tablename where Type=a.Type)

caiyunxia 2003-12-12
  • 打赏
  • 举报
回复
select type ,max(date) from table group by type
caiyunxia 2003-12-12
  • 打赏
  • 举报
回复
select a,max(date) from table group by a

22,209

社区成员

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

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