2

表“交易”是所有交易的列表,其中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)。

4

1 回答 1

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);
于 2013-04-25T14:21:27.363 回答