在Oracle中,如何在聚合所有行时选择特定行

时间:2016-10-07 23:19:24

标签: sql oracle

我要求我需要通过id聚合所有行,并在相同id的行中找到1个特定行。它类似于2个SQL查询,但我想在1个SQL查询中进行查询。我正在使用Oracle数据库。 例如,表t1的数据如下:

id   |  name  | num
----- -------- -------
1    |  'a'   |   1
2    |  'b'   |   3
2    |  'c'   |   6
2    |  'd'   |   6

我想按ID汇总数据,找到' name'最高'计数',并将所有ID计入总数' total_count'。 有两行有相同的数字,拿起第一行。

id   | highest_num | name_of_highest_num |  total_num |  avg_num 
----- ------------- --------------------- ------------ -------------------
1    |      1      |          'a'        |     1      |     1
2    |      6      |          'c'        |     15     |     5

我可以通过1个Oracle SQL查询获得此结果吗? 提前感谢您的回复。

3 个答案:

答案 0 :(得分:4)

Oracle安装程序

CREATE TABLE table_name ( id, name, num ) AS
SELECT 1, 'a', 1 FROM DUAL UNION ALL
SELECT 2, 'b', 3 FROM DUAL UNION ALL
SELECT 2, 'c', 6 FROM DUAL UNION ALL
SELECT 2, 'd', 6 FROM DUAL;

<强>查询

SELECT id,
       MAX( num ) AS highest_num,
       MAX( name ) KEEP ( DENSE_RANK LAST ORDER BY num ) AS name_of_highest_num,
       SUM( num ) AS total_num,
       AVG( num ) AS avg_num
FROM   table_name
GROUP BY id

<强>输出

ID HIGHEST_NUM NAME_OF_HIGHEST_NUM TOTAL_NUM AVG_NUM
-- ----------- ------------------- --------- -------
 1           1 a                           1       1 
 2           6 d                          15       5 

答案 1 :(得分:1)

听起来你想要使用一些分析功能。这样的事情应该有效

select id,
       num highest_num,
       name name_of_highest_num,
       total total_num,
       average avg_num
  from (select id,
               num, 
               name,
               rank() over (partition by id
                                order by num desc, name asc) rnk,
               sum(num) over (partition by id) total,
               avg(num) over (partition by id) average
          from table t1)
 where rnk = 1

答案 2 :(得分:1)

以下是使用row_number的子查询中使用conditional aggregation的一个选项:

select id, 
  max(num) as highest_num,
  max(case when rn = 1 then name end) as name_of_highest_num,
  sum(num) as total_num,
  avg(num) as avg_num
from (
  select id, name, num, 
    row_number() over (partition by id order by num desc) rn
  from a
  ) t
group by id