简体   繁体   English

从平均值计算总和

[英]calculating a sum from an average

I have a table with the following attributes; 我有一个具有以下属性的表; inv_num , inv_amount inv_numinv_amount

I want to create a query that displays both inv_num and inv_amount and also the average of the inv_amount as avg-inv and the difference of the inv_amount-avg_inv 我想创建一个显示inv_num和inv_amount以及inv_amount的平均值作为avg-inv和inv_amount-avg_inv的差的查询

So far I'm able to get the average but I cant seem to figure out how to get the difference between the calculated average and the inv_amount. 到目前为止,我已经能够获得平均值,但是我似乎无法弄清楚如何获得计算出的平均值与inv_amount之间的差。

SELECT  inv_num, 
        inv_amount, 
        (select avg(inv_amount) from invoice) as avg_inv
from invoice
; 

I recommend using a JOIN operation to an inline view. 我建议对内联视图使用JOIN操作。 For example: 例如:

    SELECT i.inv_num 
         , i.inv_amount
         , a.avg_inv
         , i.inv_amount - a.avg_inv   AS diff
      FROM invoice i
     CROSS
      JOIN ( SELECT AVG(t.inv_amount) AS avg_inv
               FROM invoice t
           ) a

The inline view (aliased as a ) returns a single row, with column avg_inv . 共线视图(别名为a )返回单行,用柱avg_inv That row gets matched with all rows returned from i , so avg_inv is available to use in expression in the SELECT list of the outer query. 该行与从i返回的所有行匹配,因此avg_inv可在外部查询的SELECT列表的表达式中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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