求一SQL写法。表结构与数据都有了。

[复制链接]
查看11 | 回复9 | 2006-7-20 13:19:20 | 显示全部楼层 |阅读模式
CREATE TABLE TestTb (a varchar2(21), b int ,c int);
13400000000,1,9
13400000001,1,9
13400000002,1,9
13400000003,1,9
13400000001,1,7
13400000001,2,8
13400000001,3,7
/*求a记录集,如果a有多个值相同,取c最小的,如果还有多个a相同,取b最大的 */
表中不存在a\b\c三列都相同的数据。
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
写一个嵌套子查询就可以实现。
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
Select a,Min(c),Max(b) From testtb Group By a
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
最初由 junsansi 发布
[B]Select a,Min(c),Max(b) From testtb Group By a [/B]

这个不行的,和数据有关系,只好使用分析函数了。
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
想了半天,还是没有写出简单点的,太复杂了写的.
select
distinct a,
first_value(b) over(partition by a order by rownum ) b,
first_value(c) over(partition by a order by rownum) c
from(SELECT a, b, c
FROM testtb ORDER BY a, c asc, b desc)
order by a asc;
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
a记录集,如果a有多个值相同,取c最小的,如果还有多个a相同,取b最大的
怎么看都是病句
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
应该不是病句,用分析函数可以实现的
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
SQL> CREATE TABLE TestTb (a varchar2(21), b int ,c int);
Table created
SQL> insert into testtb values(13400000000,1,9);
1 row inserted
SQL> insert into testtb values(13400000001,1,9);
1 row inserted
SQL> insert into testtb values(13400000002,1,9);
1 row inserted
SQL> insert into testtb values(13400000003,1,9);
1 row inserted
SQL> insert into testtb values(13400000001,1,7);
1 row inserted
SQL> insert into testtb values(13400000001,2,8);
1 row inserted
SQL> insert into testtb values(13400000001,3,7);
1 row inserted
SQL> commit;
Commit complete
SQL> select distinct a,d from(
2select a,b,c,
3max(b) keep (DENSE_RANK first ORDER BY c) over(partition by a) d
4from testtb
5) order by a;
A
D
--------------------- ----------
13400000000
1
13400000001
3
13400000002
1
13400000003
1
SQL>


KEEP的详细用法参看下边帖子的84楼:[/COLOR]
http://www.itpub.net/showthread. ... 10&pagenumber=9



回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
似乎LZ是这样的意思
SQL>select a,b,c from (
select a,b,c,
row_number() over(partition by a order by a,c,b desc) rn
from testtb
) where rn=1;
A B C
--------------------- ----------
13400000000 1 9
13400000001 3 7
13400000002 1 9
13400000003 1 9
SQL>
回复

使用道具 举报

千问 | 2006-7-20 13:19:20 | 显示全部楼层
谢谢各位
天外飞仙帮我想了这样的:
select tb.a,max(tb.b),tb.c from
(select a,min(c) c from TestTb group by a) ta,TestTb tb
where ta.a=tb.a and ta.c=tb.c group by tb.a,tb.c
实现了功能也很快谢谢天外飞仙了。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行