从Group By创建的两个聚合列中获取平均列

时间:2019-05-08 11:37:45

标签: sql oracle

我目前已使用以下函数创建了一个表

SELECT c.cus_code, cus_balance,
       SUM (line_units * line_price) AS "Total Purchases",
       COUNT (line_number) AS "Number of Purchases"
FROM customer c JOIN invoice i ON c.cus_code = i.cus_code
JOIN line l ON i.inv_number = l.inv_number
GROUP BY c.cus_code, cus_balance
ORDER BY cus_code;

现在,我想通过将上述分组依据表结果中的"Average Purchase"除以"Total Purchases"/"Number of Purchases"列来扩展此表。我在实现最后一列时遇到问题,因为我需要使用分组依据数据来计算最后一列。

帮助?

2 个答案:

答案 0 :(得分:2)

您为什么不只使用AVG()

SELECT c.cus_code, cus_balance,
       SUM(line_units * line_price) AS "Total Purchases",
       COUNT(line_number) AS "Number of Purchases",
       AVG(line_units * line_price) as "Average Purchase"
FROM customer c JOIN 
     invoice i
     ON c.cus_code = i.cus_code JOIN
     line l
     ON i.inv_number = l.inv_number
GROUP BY c.cus_code, cus_balance
ORDER BY cus_code;

这确实假设line_number不是NULL。这似乎是一个合理的假设,但是如果可以为NULL,则可能需要对表达式进行除法。

答案 1 :(得分:1)

只需添加另一列,例如-

(SUM (line_units * line_price)*1.00)/(COUNT (line_number)) AS "Average Purchase"