读书人

也是一个数据排序有关问题

发布时间: 2012-03-09 21:42:54 作者: rapoo

也是一个数据排序问题
年 月 id
2007 1 XX2
2007 3 XX3
2007 3 XX4
2007 3 XX5
2007 2 XX6
2006 5 XX7
2006 5 XX8
2006 4 XX9

怎样才能select出来每年每月只一条显示?

是不是感觉还差其他条件啊,如果没有其他约束,这上面能不能用语句显示出来呢
是不是这样才是正常的,每年每月ID最大的

[解决办法]
如果只有三字段

Select 年, 月, Max(id) As id From 表 Group By 年, 月
[解决办法]
--如果有的字段

--方法一
Select * From 表 A Where Not Exists(Select id From 表 Where 年 = A.年 And 月 = A.月 And id > A.id)

--方法二
Select * From 表 A Where id = (Select Max(id) From 表 Where 年 = A.年 And 月 = A.月)

--方法三
Select A.* From 表 A
Inner Join
(Select 年, 月, Max(id) As id From 表 Group By 年, 月) B
On A.年 = B.年 And A.月 = B.月 And A.id = B.id
[解决办法]
create table test(Y int,M int,id int)
insert test select '2007 ', '1 ', '002 '
union all select '2007 ', '3 ', '003 '
union all select '2007 ', '3 ', '004 '
union all select '2007 ', '3 ', '005 '
union all select '2007 ', '2 ', '006 '
union all select '2006 ', '5 ', '007 '
union all select '2006 ', '5 ', '008 '
union all select '2006 ', '4 ', '009 '
select * from test

select Y,M,Max(id) M from test group by Y,M

/-----------------------/
年 月 ID
200712
200726
200735
200649
200658

读书人网 >SQL Server

热点推荐