这样的sql要怎么写?

gmaxajtg 2004-10-15 10:40:50
求教sql
原数据:
A B C
1 2 4
1 2 3
2 3 4
3 3 5
输出:
A B C
1 2 4
2 3 4
3 3 5
如果A相同,取C最大值的记录(a值不能有重复)
最好是用一句SQL语句得出接果,有办法没?
...全文
119 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
freddy2003 2004-10-15
  • 打赏
  • 举报
回复
select a,b,c from (select a,b,c,sum(1) over(partition by a order by c desc) num from t4) tmp where tmp.num=1;
yjdn 2004-10-15
  • 打赏
  • 举报
回复
--上面写错了
--建表
create table tn(A int,B int,C int);
insert into tn select 1, 2, 4 from dual
union all select
1, 2, 3
from dual
union all select
2 ,3, 4
from dual
union all select
3 ,3, 5
from dual;

--测试
select * from tn where C in (select max(C)from tn a group by A);

--结果

A B C
---------- ---------- ----------
1 2 4
2 3 4
3 3 5

wylwyl1130 2004-10-15
  • 打赏
  • 举报
回复
写错了一点
select * from tbname a where a.C =(select max(b.C) from tbname b where a.A=b.A)
wylwyl1130 2004-10-15
  • 打赏
  • 举报
回复
select * from tbname a where a.C =(select max(b.rowid) from tbname b where a.A=b.A)
bzszp 2004-10-15
  • 打赏
  • 举报
回复
select * from (select tb.*,rank() over(partition by a order by c desc) rk) t
where r.rk=1;
yjdn 2004-10-15
  • 打赏
  • 举报
回复
select A,B=(select B from 表名 where C=max(a.C)),max(C) from 表名 a group by A ;
biliky 2004-10-15
  • 打赏
  • 举报
回复
先对所有记录按照字段A分组,再在每组中取C最大值,两种法方法:
方法一:
select a,b,c from (select a,b,c,rank() over(partition by a order by c desc) rank from tab ) t
where t.rank=1;
方法二:
select k.a,t.b,k.c from (select a,max(c) c from tab group by a) k,tab t where t.c=k.c and t.a=k.a;
yang2004 2004-10-15
  • 打赏
  • 举报
回复
select DISTINCT(t1.a),t2.b,t1.c
from (select a,max(c) c from table group by a) t1,table t2
where t1.a=t2.a and
t1.c=t2.c;
gmaxajtg 2004-10-15
  • 打赏
  • 举报
回复
只要求a不同,C最大,并把B的值也例出来,至于A ,C可能有多条相同的,那么最先找到的C最大的记录优先,和要求并不冲突。再说了,yjdn(无尽天空) 的sql并没有达到要求.

我把sql都测试了,以下都能达到要求:
select * from tbname a where a.C =(select max(b.C) from tbname b where a.A=b.A)

select a,b,c from (select a,b,c,sum(1) over(partition by a order by c desc) num from t4) tmp where tmp.num=1;
flyhenry 2004-10-15
  • 打赏
  • 举报
回复
楼主的题有问题,“如果A相同,取C最大值的记录(a值不能有重复)”,要是有两个记录A,C相同且C最大,那要求怎么取呢?要是都取就肯定A重复;
其他人的我没看,就yjdn(无尽天空)的答案,齐是一下子就看出来有问题了,最简单的例子,再增加一条记录
INSERT INTO TN(A,B,C) VALUES('4','3','3'),你看结果是什么?是不是五条记录全出来了
其实很简单了只要 SELECT A,B,MAX(C) FROM TN GROUP BY A,B 就可以了,但这样会出现C最大,B不同,A重复的问题。

17,082

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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