科目      年          余额
1001      2006       100
1001      2007       50
1001      2008       120
1003      2007       100
1003      2008       80
1004      2006       120
1004      2007       158
1005      2006       220
要求得出以下结果
科目      年          余额
1001      2008       120
1003      2008       80
1004      2007       158
1005      2006       220
怎么写SQL   
求出每个科目最近的一条记录

解决方案 »

  1.   


    select 科目,余额,max(年) from table
    group by 科目,余额
      

  2.   

    select 1001 科目,2006 年,100 余额 into #t union 
    select 1001,2007,50 union
    select 1001,2008,120 union
    select 1003,2007,100 union
    select 1003,2008,80 union
    select 1004,2006,120 union
    select 1004,2007,158 union
    select 1005,2006,220 
    select * from #t t where 年=(select max(年) from #t where 科目=t.科目)
      

  3.   

    --> liangCK小梁 于2008-10-19
    --> 生成测试数据: #T
    IF OBJECT_ID('tempdb.dbo.#T') IS NOT NULL DROP TABLE #T
    CREATE TABLE #T (科目 INT,年 INT,余额 INT)
    INSERT INTO #T
    SELECT 1001,2006,100 UNION ALL
    SELECT 1001,2007,50 UNION ALL
    SELECT 1001,2008,120 UNION ALL
    SELECT 1003,2007,100 UNION ALL
    SELECT 1003,2008,80 UNION ALL
    SELECT 1004,2006,120 UNION ALL
    SELECT 1004,2007,158 UNION ALL
    SELECT 1005,2006,220--SQL查询如下:SELECT *
    FROM #T AS t
    WHERE 年=(SELECT MAX(年)
              FROM #T
              WHERE t.科目=科目)
    ORDER BY 科目/*
    科目          年           余额
    ----------- ----------- -----------
    1001        2008        120
    1003        2008        80
    1004        2007        158
    1005        2006        220(4 行受影响)*/
      

  4.   

    select * from tb t where not exists(select 1 from tb where 科目=t.科目 and 年>t.年)
      

  5.   

    declare @t table(科目 int,      年 int,         余额 int)
    insert @t select 1001   ,   2006 ,     100 
    insert @t select 1001   ,   2007 ,     50 
    insert @t select 1001   ,   2008 ,     120 
    insert @t select 1003   ,   2007 ,     100 
    insert @t select 1003   ,   2008 ,     80 
    insert @t select 1004   ,   2006 ,     120 
    insert @t select 1004   ,   2007 ,     158 
    insert @t select 1005   ,   2006 ,     220 
    select * from @T t where not exists(select 1 from @t where 科目=t.科目 and 年>t.年)
    /*
    科目          年           余额          
    ----------- ----------- ----------- 
    1001        2008        120
    1003        2008        80
    1004        2007        158
    1005        2006        220*/
      

  6.   

    刚写的有错,重新写了下:select t1.科目,t1.年,t2.余额 from (select 科目,max(年) as 年 from 表 group by 科目) t1
    left outer join 表 t2
    on t1.科目 = t2.科目 and t1.年 = t2.年