简体   繁体   中英

AVG() is replicating data stored in the row and not providing the average number for the column

I've created a query to retrieve data from multiple columns. However, when using the AVG(*) AVERAGE to display the value for a given column, the function simply replicates and displays the data in each row. I essentially want the table to display each column in the query and display the table average in each row.

If I don't have multiple columns in the select statement then I can query the table to display the true average for the given column just fine. I have tried using using UNIONs and SELF JOINs to query the AVG(*) AVERAGE, but with no luck.

CREATE TABLE INVOICE
(
    INV_NUM NUMBER NOT NULL PRIMARY KEY,
    CUST_NUM NUMBER NOT NULL REFERENCES CUSTOMER(CUST_NUM),
    INV_DATE DATE NOT NULL,
    INV_AMOUNT NUMBER NOT NULL
);


INSERT ALL
INTO (INV_NUM,CUST_NUM,INV_DATE,INV_AMOUNT) 
VALUES ('8000','1000','3/23/2014','235.89')


INTO (INV_NUM,CUST_NUM,INV_DATE,INV_AMOUNT) 
VALUES ('8001','1001','3/23/2014','312.82')


INTO (INV_NUM,CUST_NUM,INV_DATE,INV_AMOUNT) 
VALUES ('8002','1002','3/30/2014','528.10')       


INTO (INV_NUM,CUST_NUM,INV_DATE,INV_AMOUNT) 
VALUES ('8003','1003','4/12/2014','194.78')


INTO (INV_NUM,CUST_NUM,INV_DATE,INV_AMOUNT) 
VALUES ('8004','1004','4/23/2014','619.44')

SELECT * FROM DUAL;

--------------TABLE QUERIES----------------

SELECT INV_NUM, INV_AMOUNT, AVG(INV_AMOUNT) AVERAGE, 
AVG(INV_AMOUNT)-INV_AMOUNT DIFFERENCE
FROM INVOICE
GROUP BY INV_NUM, INV_AMOUNT;

Something like this:

with invoice as (
select 
8000 INV_NUM,1000 CUST_NUM,'3/23/2014' INV_DATE,235.89 INV_AMOUNT
from dual union all
select 8001,1001,'3/23/2014',312.82
from dual union all
select 8002,1002,'3/30/2014',528.10
from dual union all
select 8003,1003,'4/12/2014',194.78
from dual union all
select 8004,1004,'4/23/2014',619.44 from dual)
SELECT INV_NUM, INV_AMOUNT, AVERAGE, 
AVERAGE-INV_AMOUNT DIFFERENCE
FROM INVOICE,(select avg(inv_amount) average from invoice)
ORDER BY INV_NUM, INV_AMOUNT

You are aggregating by INV_NUM and INV_AMT , so you have not done any aggregation at all.

I think you want an analytic function instead of aggregation:

SELECT INV_NUM, INV_AMOUNT,
       AVG(INV_AMOUNT) OVER () as AVERAGE, 
       (AVG(INV_AMOUNT) OVER () - INV_AMOUNT) as DIFFERENCE
FROM INVOICE;

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