求一SQL语句

lqdmafeng 2006-06-07 12:06:33
如何从下面数据

id aa_id money amonth ayear
1 1 32 1 2005
2 1 34 2 2005
3 2 234 1 2005
4 2 5645 2 2005
5 2 34 3 2005
6 1 324 2 2006
7 1 43534 6 2006

得到:
id aa_id money amonth ayear
2 1 34 2 2005
5 2 34 3 2005
7 1 43534 6 2006

也就是说,如何得到相同aa_id,相同ayear,amonth最大的数据.
谢谢!
...全文
149 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
liangpei2008 2006-06-07
  • 打赏
  • 举报
回复
--Or
declare @t table (id int,aa_id int ,money int,amonth int,ayear int)
insert @t select 1,1,32,1,2005
union all select 2,1,34,2,2005
union all select 3,2,234,1,2005
union all select 4,2,5645,2,2005
union all select 5,2,34,3,2005
union all select 6,1,324,2,2006
union all select 7,1,43534,6,2006


select * from @t A
where id in (select top 1 id from @t where aa_id=A.aa_id and ayear=A.ayear order by amonth desc)
liangpei2008 2006-06-07
  • 打赏
  • 举报
回复
刚才错了:)
declare @t table (id int,aa_id int ,money int,amonth int,ayear int)
insert @t select 1,1,32,1,2005
union all select 2,1,34,2,2005
union all select 3,2,234,1,2005
union all select 4,2,5645,2,2005
union all select 5,2,34,3,2005
union all select 6,1,324,2,2006
union all select 7,1,43534,6,2006
select * from @t A
where not exists
( select 1 from @t where A.aa_id=aa_id and A.ayear=ayear and amonth>A.amonth)
lxzm1001 2006-06-07
  • 打赏
  • 举报
回复
select v.* from view1 v inner join (select max(amonth) as maxmonth,aa_id, ayear from view1 group by aa_id,ayear) x on v.aa_id=x.aa_id and v.ayear=x.ayear and v.amonth=x.maxmonth
liangpei2008 2006-06-07
  • 打赏
  • 举报
回复
楼上快!:)
liangpei2008 2006-06-07
  • 打赏
  • 举报
回复
select * from table1 A
where not exists
( select 1 from table1 where A.aa_id=aa_id and A.ayear=ayear and amonth<A.amonth)
lxzm1001 2006-06-07
  • 打赏
  • 举报
回复
select * from tablename t not exists(select 1 from tablename aa_id=t.aa_id and ayear=t.ayear and amonth>t.amonth)
lqdmafeng 2006-06-07
  • 打赏
  • 举报
回复
我现在写的SQL语句可以得到三列的值,如何得到全部列的值呢:

SQL语句如下:
select max(amonth) as maxmonth,aa_id, ayear from view1 group by aa_id,ayear

十一月猪 2006-06-07
  • 打赏
  • 举报
回复

select * from tab a
where not exists(select 1 from tab b where a.aa_id = b.aa_id and a.id < b.id )

or

select a.* from tab a ,
(
select max(id) as id, aa_id
from tab group by aa_id
) b
where a.id = b.id and a.aa_id = b.aaid

34,588

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧