表“交易”是所有交易的列表,其中date
, customerID
, 每单位成本 ( 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)。