首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求SQL,分类查询语句,写法!该怎么处理

2012-04-26 
求SQL,分类查询语句,写法!表:ID,类型,时间,其它1A2012-04-23 18:00:002A2012-04-24 18:00:003A2012-04-25

求SQL,分类查询语句,写法!
表:
ID,类型,时间,其它

1 A 2012-04-23 18:00:00
2 A 2012-04-24 18:00:00 
3 A 2012-04-25 18:00:00
5 B 2012-04-23 18:00:00
6 B 2012-04-24 18:00:00 
7 C 2012-04-25 18:00:00
8 C 2012-04-23 18:00:00


我要按分类查询,得到 A,B,C中,时间最大的记录各1条。

我要的结果:

3 A 2012-04-25 18:00:00
6 B 2012-04-24 18:00:00
7 C 2012-04-25 18:00:00

这语法这么写?

[解决办法]

SQL code
select 类型,       时间from 表 twhere id in(select top 1 id from 表 where 类型=t.类型 order by 时间 desc)
[解决办法]
SQL code
if object_id('[TB]') is not null drop table [TB]gocreate table [TB] (ID int,类型 nvarchar(2),时间 datetime,其它 sql_variant)insert into [TB]select 1,'A','2012-04-23 18:00:00',null union allselect 2,'A','2012-04-24 18:00:00',null union allselect 3,'A','2012-04-25 18:00:00',null union allselect 5,'B','2012-04-23 18:00:00',null union allselect 6,'B','2012-04-24 18:00:00',null union allselect 7,'C','2012-04-25 18:00:00',null union allselect 8,'C','2012-04-23 18:00:00',nullselect * from [TB]select distinct B.ID,B.类型,B.时间from TB Across apply(select top 1 ID,类型,时间 from TB where 类型 = A.类型 order by 时间 desc) B/*3    A    2012-04-25 18:00:00.0006    B    2012-04-24 18:00:00.0007    C    2012-04-25 18:00:00.000*/
[解决办法]
SQL code
;with TTas(select ROW_NUMBER() over(PARTITION by 类型 order by 时间 desc )as nn ,* from TB)select ID,类型,时间 from TT where nn = 1 

热点排行
Bad Request.