表 TB,一共 4 个 字段年      月       合同号       合同量
2010    1         PG1          100
2010    2         PG1          200
2011    1         PG2          300
2011    2         PG2          400我想取得结果是2010    2         PG1          200
2011    2         PG2          400即,最晚的那个合同号的数据,也就是 年、月最大的那个

解决方案 »

  1.   

    select *
    from tb t
    where not exists(select 1
                     from tb
                     where (合同号=t.合同号 and 年>t.年) or 合同号=t.合同号 and 年=t.年 and 月>t.月)
      

  2.   

    SELECT b.* FROM 
    (SELECT DISTINCT 合同号 FROM tb) a
    CROSS APPLY
    (SELECT TOP(1) * FROM tb WHERE 合同号=a.合同号 ORDER BY 年 desc,月 desc) b
      

  3.   

    select T.年,T.月,T.合同号,T.合同量 from (
    select A.*,row_number() over(partition by A.合同号 order by A.月 desc ) as row from TB as A
    ) AS T where T.row = 1
      

  4.   

    create table tb(年 char(4),月 char(2),合同号 varchar(10),合同量 varchar(10))
    insert into tb
    select '2010','1','PG1','100' union all
    select '2010','2','PG1','200' union all
    select '2011','1','PG2','300' union all
    select '2011','2','PG2','400'
    select a.年,a.月,a.合同号,a.合同量 from tb a inner join
    (select max(年) as 年,max(月) as 月 from tb group by 合同号) b on a.年=b.年 and a.月=b.月
      

  5.   

    看来我的SQL知识老化了,学习
      

  6.   

    select
     *
    from
     tb t
    where
     not exists(select 1 from tb where (合同号=t.合同号 and 年>t.年) or (合同号=t.合同号 and 年=t.年 and 月>t.月))
      

  7.   


    use tempdb;
    /*
    create table tb
    (
    [年] int not null,
    [月] int not null,
    [合同号] nvarchar(10) not null,
    [合同量] int not null
    );
    insert into tb([年],[月],[合同号],[合同量])
    values
    (2010,1,'PG1',100),
    (2010,2,'PG1',200),
    (2011,1,'PG2',300),
    (2011,2,'PG2',400);
    */
    select *
    from tb as t2
    where exists
    (
    select t1.[年],MAX(t1.[月]) as [月]
    from tb as t1
    group by t1.[年]
    having t1.[年] = t2.[年] and MAX(t1.[月]) = t2.[月]
    );