比如表数据如下:
工号   日期          数量
H001   2006-03-10    5
H001   2006-03-20    2
H001   2006-04-01    0
H002   2006-05-01    2
....
--------------------
需要查询:
根据每个工号,查最后一次(日期最大)的记录,
工号   日期          数量
H001   2006-04-01    0
H002   2006-05-01    2
----
工号不重复,日期最大的那个记录。

解决方案 »

  1.   

    select * from t , (select 工号, max(日期) as 日期 from t group by 工号) t1
    where t.工号 = t1.工号 and t.日期 = t1.日期
      

  2.   

    SELECT * FROM TB A WHERE NOT EXISTS(SELECT 1 FROM TB WHERE 工号=A.工号 AND 日期>A.日期)
      

  3.   

    select * from table a
    where not exists(select 1 from table where 工号 = a.工号 and 日期 > a.日期)
      

  4.   

    SELECT * FROM TB A WHERE 日期=(SELECT MAX(日期) FROM TB WHERE 工号 =A.工号 )
      

  5.   

    declare @a table (工号 varchar(4) ,  日期 datetime,  数量 int)
    insert @a
    select 'H001',   '2006-03-10',    5 union all
    select 'H001',   '2006-03-20',    2 union all
    select 'H001',   '2006-04-01',    0 union all
    select 'H002',   '2006-05-01',    2
    select * from @a b where exists 
    (select *from (select distinct 工号,日期=max(日期)from @a   group by 工号)a where 工号=b.工号 and  日期=b.日期)
    order by 工号(所影响的行数为 4 行)工号   日期                                                     数量          
    ---- ------------------------------------------------------ ----------- 
    H001 2006-04-01 00:00:00.000                                0
    H002 2006-05-01 00:00:00.000                                2(所影响的行数为 2 行)