假设我的数据库中有以下表格
A B C D E
2009 db1234 12345 1234567 3000
2010 db1235 34567 1234567 3100
2011 cn2345 23456 2345678 2800
2010 db1236 12345 1234567 3100
2012 db1237 34567 1234567 2800
如果我在表A上做最大功能,我会得到2012。 我希望查询返回A和相应的C列值,即34567,在SQL中。
答案 0 :(得分:4)
要获取相应列的值以及要应用聚合函数的列的值,您需要按该列进行分组。另一种方法是使用analytic functions中的一个,无论它是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