客户每月的SQL平均值

时间:2013-04-25 14:17:19

标签: sql oracle select group-by nested

“交易”表是包含datecustomerID,每单位费用(price)和quantity的所有交易的列表。

我需要一份报告,将交易分组为几个月,并计算每个客户的总收入和平均收入。

我无法弄清楚如何将group by customerID插入此select语句中:

SELECT extract(month FROM date) month,
       count(*) purchases,
       SUM(price*quantity) income,
       AVG(SUM(price*quantity)) <-- this needs to be grouped by customerID aswell as month
FROM
    transactions
WHERE
    date BETWEEN i2 AND i3
GROUP BY extract(month FROM date);

我能得到的最接近的是:

SELECT extract(month FROM date) month,
       count(*) purchases,
       SUM(price*quantity) income,
       ( SELECT AVG(SUM(price*quantity))
         FROM transactions
         GROUP BY customerID, extract(month FROM date) )
FROM
    transactions t
WHERE
    date BETWEEN i2 AND i3
GROUP BY extract(month FROM date);

但是,由于嵌套的select将返回多行,因此在我考虑它一分钟后,这种方法就停止了。如果我添加where子句并删除第二个选择中的group by date

(SELECT AVG(SUM(price*quantity))
 FROM transactions
 GROUP BY customerID
 where extract(month FROM date) = month)

然后它会回来......我不确定是什么,但这是错误的。

顺便说一句,它是一个oracle数据库(我认为是10g)。

1 个答案:

答案 0 :(得分:2)

您可以使用算术来完成此操作。 。 。将总数除以客户数量:

SELECT extract(month FROM date) month,
       count(*) purchases,
       SUM(price*quantity) income,
       sum(price*quantity) / count(distinct customerId)
FROM
    transactions
WHERE
    date BETWEEN i2 AND i3
GROUP BY extract(month FROM date);