主题:求SQL語句!!
zyw222
[专家分:0] 发布于 2007-02-01 16:29:00
有一張表
ID SubID intSum Type
1 1 1 A
1 1 2 B
1 1 1 C
1 2 1 A
1 2 3 B
2 1 1 C
2 1 3 D
......
我要以ID,SubID分組(不能對Type分組),返回intSum最大的一記錄:
ID SubID intSum Type
1 1 2 B
1 2 3 B
2 1 3 D
請教這樣的SQL如何寫啊
回复列表 (共3个回复)
沙发
ilovemountainking [专家分:3730] 发布于 2007-02-01 21:06:00
假设表名为a,则可以这样子写:
select * from a outer where outer.intsum = (select max(intsum) from a inner
group by id,subid)
板凳
棉花糖ONE [专家分:90] 发布于 2007-02-16 21:29:00
declare @t table(aa int,bb int,cc int,dd char(1))
insert into @t select 1,1,1,'A'
insert into @t select 1,1,2,'B'
insert into @t select 1,1,1,'C'
insert into @t select 1,2,1,'A'
insert into @t select 1,2,3,'B'
insert into @t select 2,1,1,'C'
insert into @t select 2,1,3,'D'
select a.* from @t a inner join (select aa,bb,max(cc) as c from @t group by aa,bb) as b on a.aa=b.aa and a.bb=b.bb and a.cc=b.c order by a.aa ,a.bb
aa bb cc dd
----------- ----------- ----------- ----
1 1 2 B
1 2 3 B
2 1 3 D
3 楼
棉花糖ONE [专家分:90] 发布于 2007-02-16 21:31:00
select a.* from @t a where exists (select 1 from @t where aa=a.aa and bb=a.bb group by aa,bb having a.cc=max(cc)) order by aa,bb
我来回复