简体   繁体   中英

An oracle sql query to find value from the attributes

Suppose I have the following table 'player' in oracle database:

  P_ID P_NAME       C_ID      DEBUT      MATCH       RUNS

   101 amla          204       2003        190       5000
   102 mushi         200       2001        240       7500
   103 sakib         200       1999        150       5000
   104 ricky         205       1993        180       7000
   105 sachin        203       1990        250       8000
   106 yuvi          203       1999        150       6900

I need a query to display the c_id, total runs done by all batsmen of the country which has the maximum run scorer. (in this case maximum run scorer is sachin. so the query should return : c_id = 203, runs = 14900).

I have only been able to find the maximum run scorer and the country which he belongs to. the query: select c_id, runs from player where runs = (select max(runs) from player); does that. However, I am not been able to proceed further.

When you need condition on aggregate function, you must use sub-query or having clause. This return always one row, but it's wrong when more then one groups have same total:

SELECT * 
FROM (
  SELECT c_id, Sum(runs) total 
  FROM player 
  GROUP BY c_id
  ORDER BY total DESC 
) WHERE ROWNUM =1;

But you can get all using this:

SELECT c_id, Sum(runs) total 
FROM player 
GROUP BY c_id 
HAVING Sum(runs) = (
  SELECT Max(t) from (
    SELECT Sum(runs) t 
    FROM player 
    GROUP BY c_id))
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM