I am still learning Oracle SQL and would like your guidance.
Let's say we have a table MONTHLY_SALES_TOTALS, which has 3 fields: name , region , amount . We need to identify the best sellers in each region. The best means that their number is equal to the maximum for the region.
CREATE TABLE montly_sales_totals ( name varchar(20), amount numeric(9), region varchar(30) ); INSERT ALL INTO montly_sales_totals (name, amount, region) VALUES ('Peter', 55555, 'east') INTO montly_sales_totals (name, amount, region) VALUES ('Susan', 55555, 'east') INTO montly_sales_totals (name, amount, region) VALUES ('Mark', 1000000, 'south') INTO montly_sales_totals (name, amount, region) VALUES ('Glenn', 50000, 'east') INTO montly_sales_totals (name, amount, region) VALUES ('Paul', 500000, 'south') SELECT * from dual;
Possible Solution:
SELECT m1.name, m1.region, m1.amount FROM montly_sales_totals m1 JOIN (SELECT MAX(amount) max_amount, region FROM montly_sales_totals GROUP BY region) m2 ON (m1.region = m2.region) WHERE m1.amount = m2.max_amount ORDER by 2,1;
SQL Fiddle: http://sqlfiddle.com/#!4/6a2d8/6
Now my questions are:
- How effective is such a request?
- How can / should be simplified and / or improved?
- I could not use Top , since the number of lines "max" depends on the region. Is this another direct functionality that I could use instead?
source share