比如A表:name   date
A      2012.01
A      2012.02
A      2012.03B      2012.02
B      2012.03
B      2012.04C      2012.03
C      2012.04
C      2012.05最终得到数据为:
A   2012.03
B   2012.04
C   2012.05得到每个人时间最大的数据。
Sql语句该如何写呢?谢谢。

解决方案 »

  1.   


    select a.name,date a.from(
    select row_number()over(partition by name order by cast(right(date,2) as int) desc) as num,*from tbl)a
    where num=1
      

  2.   


    CREATE TABLE #t(NAME CHAR(2),dates DATE)
    insert into #t
    select 'A', '201201' union all
    select 'A', '201202' union all
    select 'A', '201203' union allselect 'B', '201202' union all
    select 'B', '201203' union all
    select 'B', '201204' union allselect 'C', '201203' union all
    select 'C', '201204' union all
    select 'C', '201205'
    SELECT NAME,MAX(dates) FROM #t
    GROUP BY NAME
      

  3.   


    我是要得到最大时间的整条数据,如果在加个price字段等,又该如何解决呢?望指教,谢谢
      

  4.   

    select * from A t
    where not exists(select 1 from name=t.name and [date]>t.[date])
      

  5.   

    declare @t table(NAME CHAR(2),dates datetime,price decimal,typeId int)
    insert into @t
    select 'A', '201201',12.00,1 union all
    select 'A', '201202',12.00,1 union all
    select 'A', '201203',14.00,1 union all
    select 'A', '201203',14.00,1 union all
    select 'A', '201203',14.00,2 union allselect 'B', '201202',12.00,1 union all
    select 'B', '201203',12.00,2 union all
    select 'B', '201204',12.00,3 union allselect 'C', '201203',12.00,1 union all
    select 'C', '201204',12.00,1 union all
    select 'C', '201205',12.00,1 union all
    select 'C', '201205',12.00,2 union all
    select 'C', '201205',12.00,3 
    SELECT * FROM @T A
    WHERE dates = (SELECT TOP 1 dates FROM @T WHERE NAME = A.NAME and typeId=2 ORDER BY dates DESC) and typeId=2解决啦,谢谢各位。
      

  6.   

    declare @t table(NAME CHAR(2),dates datetime,price decimal,typeId int)
    insert into @t
    select 'A', '201201',12.00,1 union all
    select 'A', '201202',12.00,1 union all
    select 'A', '201203',14.00,1 union all
    select 'A', '201203',14.00,1 union all
    select 'A', '201203',14.00,2 union allselect 'B', '201202',12.00,1 union all
    select 'B', '201203',12.00,2 union all
    select 'B', '201204',12.00,3 union allselect 'C', '201203',12.00,1 union all
    select 'C', '201204',12.00,1 union all
    select 'C', '201205',12.00,1 union all
    select 'C', '201205',12.00,2 union all
    select 'C', '201205',12.00,3 
    SELECT * FROM @T A
    WHERE dates = (SELECT TOP 1 dates FROM @T WHERE NAME = A.NAME and typeId=2 ORDER BY dates DESC) and typeId=2