序号 名称 区属 日期
1 A 上 2007-7-5
4 A 下 2007-7-6
5 A 上 2007-7-4
8 A 下 2007-7-5得到:序号 名称 区属 日期
1 A 上 2007-7-5
4 A 下 2007-7-6就是找以 同名称 同区属里 最最新记录!
1 A 上 2007-7-5
4 A 下 2007-7-6
5 A 上 2007-7-4
8 A 下 2007-7-5得到:序号 名称 区属 日期
1 A 上 2007-7-5
4 A 下 2007-7-6就是找以 同名称 同区属里 最最新记录!
where not exists (
select 1 from tablename
where 名称=a.名称
and 区属=a.区属
and 日期>a.日期
)
from tableName
group by 名称, 区属
select * from tab t where exists(select 1 from tab where t.名称=名称 and t.区属=区属 and t.日期>日期)
where 日期= (
select max(日期) from tablename
where 名称=a.名称
and 区属=a.区属
)
insert tab
select 1,'A','上','2007-7-5'
union select 4,'A','下','2007-7-6'
union select 5,'A','上','2007-7-4'
union select 8,'A','下','2007-7-5'
select * from tab t where exists(select 1 from tab where t.名称=名称 and t.区属=区属 and t.日期>日期)
insert into tselect 1, 'A', '上', '2007-7-5' union all
select 4, 'A', '下', '2007-7-6' union all
select 5, 'A', '上', '2007-7-4' union all
select 8, 'A', '下', '2007-7-5'select * from t a
where exists(select 1 from t where 名稱=a.名稱 and 區屬=a.區屬 and 日期<a.日期 )序號 名稱 區屬 日期
----------- ---------- ---------- ----------
1 A 上 2007-7-5
4 A 下 2007-7-6(2 row(s) affected)
where 日期= (
select max(日期) from tablename
where 名称=a.名称
and 区属=a.区属
)tablename a ??????是什么意思?
where exists(select 1 from t where 名称=a.名称 and 区属=a.区属 and a.日期> 日期 )序号 名称 区属 日期
----------- ---------- ---------- ----------
1 A 上 2007-7-5
4 A 下 2007-7-6
select * from t a
where not exists (
select 1 from t
where 名称=a.名称
and 区属=a.区属
and 日期>a.日期
)
declare @t table(序号 int identity(1,1),名称 nvarchar(40),区属 nvarchar(40),日期 datetime)
insert into @t select 'A','上','2007-7-5'
insert into @t select 'A','下','2007-7-6'
insert into @t select 'A','上','2007-7-4'
insert into @t select 'A','下','2007-7-5'
select max(日期),名称,区属
from @t
group by 名称,区属