比如表数据如下:
工号 日期 数量
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
----
工号不重复,日期最大的那个记录。
工号 日期 数量
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
----
工号不重复,日期最大的那个记录。
where t.工号 = t1.工号 and t.日期 = t1.日期
where not exists(select 1 from table where 工号 = a.工号 and 日期 > a.日期)
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 行)