sql oracle max(总和)

时间:2016-06-30 18:59:43

标签: sql oracle greatest-n-per-group

我正在尝试在Oracle中编写一个返回最大值的查询。我有3个表员工,客户,订单。

SELECT a.ID_Employee, a.NAME, a.SURNAME, SUM(c.value) AS "value"  FROM Employee a, CUSTOMER b, ORDERS c WHERE a.ID_Employee = b.ID_Employee and b.ID_CUSTOMER = c.ID_CUSTOMER group by a.ID_Employee, a.NAME, a.SURNAME ;

问题的结果:

id_Employess Name  Surname  Value
7654         KENNETH MARTIN 27348
7555         DANIEL PETERS  11060
7820         PAUL   ROSS    20796,8
7844         MARY   TURNER  58055,9
7560         SARAH  DUNCAN  36191,2
7521         CYNTHIA WARD   9984,2
7499         KEVIN  ALLEN   7870,8
7789         LIVIA  WEST    32274,2
7557         KAREN  SHAW    33655,65

我需要这个结果的最大值应该是:

id_Employess Name  Surname  Value
7844         MARY   TURNER  58055,9

2 个答案:

答案 0 :(得分:1)

按顺序使用rownum

  select * from (
        select ID_Employee, NAME, SURNAME, value, rownum rn
         from (
        SELECT a.ID_Employee, a.NAME, a.SURNAME, SUM(c.value) AS "value"  
          FROM Employee a, CUSTOMER b, ORDERS c 
         WHERE a.ID_Employee = b.ID_Employee and b.ID_CUSTOMER = c.ID_CUSTOMER  
         group by a.ID_Employee, a.NAME, a.SURNAME 
         order by 4 desc
        )
    ) where rn = 1

答案 1 :(得分:0)

可以是此查询

select *  
from 
        (SELECT 
        a.ID_Employee
        , a.NAME
        , a.SURNAME
        , SUM(c.value) AS "value"  
        FROM Employee a, CUSTOMER b, ORDERS c 
        WHERE a.ID_Employee = b.ID_Employee 
        and b.ID_CUSTOMER = c.ID_CUSTOMER 
        group by a.ID_Employee, a.NAME, a.SURNAME ) 
 where  value  =   (SELECT  SUM(c.value)  
        FROM Employee a, CUSTOMER b, ORDERS c 
        WHERE a.ID_Employee = b.ID_Employee 
        and b.ID_CUSTOMER = c.ID_CUSTOMER 
        group by a.ID_Employee, a.NAME, a.SURNAME );