日期:2014-05-18  浏览次数:20605 次

也是一个数据排序问题
年       月     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
2007 1 2
2007 2 6
2007 3 5
2006 4 9
2006 5 8