Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
Home -> Community -> Usenet -> c.d.o.server -> "Sum distinct"
Let's say I have a sales organization (denormalized and simplified
design):
CREATE TABLE salesman (id NUMBER PRIMARY KEY, manager VARCHAR2(10),
salary NUMBER);
CREATE TABLE sale (id NUMBER PRIMARY KEY, salesman_id NUMBER REFERENCES
salesman(id), value NUMBER);
INSERT INTO salesman VALUES (1,'Manager1',10); INSERT INTO salesman VALUES (2,'Manager1',20); INSERT INTO salesman VALUES (3,'Manager1',10); INSERT INTO salesman VALUES (4,'Manager2',5); INSERT INTO sale VALUES (1,1,4); INSERT INTO sale VALUES (2,1,7); INSERT INTO sale VALUES (3,2,8); INSERT INTO sale VALUES (4,3,9);
I want a query that shows for each manager: his salesmen's total salary and the total value of their sales. The following naive query doesn't work since the salesmens' salaries will be counted once for each of their sales:
SELECT manager, SUM(salary), SUM(value)
FROM salesman,sale
WHERE salesman.id = sale.salesman_id
GROUP BY manager;
MANAGER SUM(SALARY) SUM(VALUE)
---------- ----------- ----------
Manager1 50 28 Manager2 10 7
(The salary sums I want is 40 and 5)
The best way I can figure out is to use an inline view with an analytical function, like this:
SELECT manager, SUM(q) salary, SUM(value)
FROM
(SELECT manager,
salary/COUNT(*) OVER (PARTITION BY salesman.id) q,
value
FROM salesman, sale
WHERE salesman.id = sale.salesman_id
ORDER BY manager, salesman.id)
GROUP BY manager ORDER BY manager;
MANAGER SALARY SUM(VALUE)
---------- ---------- ----------
Manager1 40 28 Manager2 5 7
Doesn't look very elegant though...
Thanks a lot! Received on Sat Dec 11 2004 - 12:43:38 CST