要获取相应列的值以及应用聚合函数的列的值,您需要按该列进行分组。另一种方法是使用其中一个分析函数,无论是row_number()还是rank(),它们的行为不同,但在某些情况下它们可能会产生相同的结果。这里有几个例子:
SQL> with t1 (A, B, C, D, E) as(
2 select 2009, 'db1234', 12345, 1234567, 3000 from dual union all
3 select 2010, 'db1235', 34567, 1234567, 3100 from dual union all
4 select 2011, 'cn2345', 23456, 2345678, 2800 from dual union all
5 select 2010, 'db1236', 12345, 1234567, 3100 from dual union all
6 select 2012, 'db1237', 34567, 1234567, 2800 from dual
7 )
8 select max(a) maxa
9 , c
10 from t1
11 group by c
12 order by 1
13 ;
结果:
MAXA C
---------- ----------
2010 12345
2011 23456
2012 34567
如果您只想返回第一行(排序很重要),您可以使用rownum
伪列过滤结果:
SQL> with t1 (A, B, C, D, E) as(
2 select 2009, 'db1234', 12345, 1234567, 3000 from dual union all
3 select 2010, 'db1235', 34567, 1234567, 3100 from dual union all
4 select 2011, 'cn2345', 23456, 2345678, 2800 from dual union all
5 select 2010, 'db1236', 12345, 1234567, 3100 from dual union all
6 select 2012, 'db1237', 34567, 1234567, 2800 from dual
7 )
8 select *
9 from (select max(a) maxa
10 , c
11 from t1
12 group by c
13 order by 1 desc
14 )
15 where rownum = 1
16 ;
结果:
MAXA C
---------- ----------
2012 34567
第二种方法是使用row_number
解析函数。
SQL> with t1 (A, B, C, D, E) as(
2 select 2009, 'db1234', 12345, 1234567, 3000 from dual union all
3 select 2010, 'db1235', 34567, 1234567, 3100 from dual union all
4 select 2011, 'cn2345', 23456, 2345678, 2800 from dual union all
5 select 2010, 'db1236', 12345, 1234567, 3100 from dual union all
6 select 2012, 'db1237', 34567, 1234567, 2800 from dual
7 )
8 select a
9 , b
10 , c
11 , d
12 , e
13 from (select a
14 , b
15 , c
16 , d
17 , e
18 , row_number() over(partition by c order by a desc) rn
19 from t1
20 )
21 where rn = 1
22 ;
结果:
A B C D E
---------- ------ ---------- ---------- ----------
2010 db1236 12345 1234567 3100
2011 cn2345 23456 2345678 2800
2012 db1237 34567 1234567 2800
如果您不想按任何列分组,您可以编写类似的查询(此处max
使用函数的分析版本):
SQL> with t1 (A, B, C, D, E) as(
2 select 2009, 'db1234', 12345, 1234567, 3000 from dual union all
3 select 2010, 'db1235', 34567, 1234567, 3100 from dual union all
4 select 2011, 'cn2345', 23456, 2345678, 2800 from dual union all
5 select 2010, 'db1236', 12345, 1234567, 3100 from dual union all
6 select 2012, 'db1237', 34567, 1234567, 2800 from dual
7 )
8 select *
9 from(select a
10 , b
11 , c
12 , d
13 , e
14 , max(a) over() mx
15 from t1
16 ) q
17 where q.a = q.mx
18 ;
结果:
A B C D E MX
---------- ------ ---------- ---------- ---------- ----------
2012 db1237 34567 1234567 2800 2012