Im trying to figure out what this code is going:

SELECT EMP_ID, SUM(INV_PRICE) AS TOTAL_SALES
FROM INVOICE
GROUP BY EMP_ID
HAVING SUM(INV_PRICE) <= AVG(INV_PRICE);

I wrote it or it was recommend to be a while a ago and now im not sure if its doing what I originally wanted it to do.

What I wanted: I have an invoice table with price and employees. I wanted to get each employees total sales and compare that to the average total sales for all employees. From there I wanted the results to show me which employees were selling below average.

Is what I have above correct?

Here is what I get when I run <= average:

enter image description here

Here is what I get when I run > average:

enter image description here

I think my main concern is making sure that it's calculating the right average. Which is the average of the sum from each employee.

有帮助吗?

解决方案 3

No, it's not. The SUM(INV_PRICE) will give you the total sales of an employee but the AVG(INV_PRICE) will give you the average sale per employee, not the average (for all employees) of their total sales.

Try this of you want the average of total sales calculated for all employees - even those that have no sales at all:

SELECT EMP_ID, SUM(INV_PRICE) AS TOTAL_SALES
FROM INVOICE
GROUP BY EMP_ID
HAVING SUM(INV_PRICE) <= 
         ( SELECT SUM(INV_PRICE) FROM INVOICE )
       / ( SELECT COUNT(*) FROM EMPLOYEE )
  ; 

or this if you want the average of all employees that have sales:

SELECT EMP_ID, SUM(INV_PRICE) AS TOTAL_SALES
FROM INVOICE
GROUP BY EMP_ID
HAVING SUM(INV_PRICE) <= 
         ( SELECT SUM(INV_PRICE) / COUNT(DISTINCT EMP_ID) 
           FROM INVOICE )
  ; 

Skip that, Access has no COUNT(DISTINCT ):

SELECT EMP_ID, SUM(INV_PRICE) AS TOTAL_SALES
FROM INVOICE
GROUP BY EMP_ID
HAVING SUM(INV_PRICE) <=
         ( SELECT AVG(TOTAL_SALES)
           FROM
             ( SELECT SUM(INV_PRICE) AS TOTAL_SALES
               FROM INVOICE
               GROUP BY EMP_ID 
             ) tmp
         ) ; 

其他提示

Is what I have above correct?

No. Your query is probably returning no records (only the ones with one sale). sum(inv_price) greater or equal that the avg(inv_price) for any given group most of the time.

You want to precalculate the average in another query.

What you want is this:

SELECT EMP_ID, SUM(INV_PRICE) AS TOTAL_SALES
FROM INVOICE
GROUP BY EMP_ID
HAVING SUM(INV_PRICE) <= (
    SELECT AVG(INV_SUM)
    FROM (
        SELECT SUM(INV_PRICE) AS INV_SUM
        FROM INVOICE
        GROUP BY EMP_ID) x) ;

The average calculated here is over the all employees, whereas your calculates it over each group, which is non-sensical: the sum can't be more than the average for any given group.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top