我在mysql数据库中有一个包含货币交易的表。假设tabled被称为 transactions :
id int,
to_user int,
from_user int,
created datetime,
amount double
我正在尝试创建一个查询,该查询返回按每天显示的交易数量分组的平均交易金额。适用的列是金额并创建。
所以我试图回答这个问题:在0到2个交易,2到4个交易,4到6个交易之间等的日子里发生的平均交易量是多少。
有什么想法吗?
答案 0 :(得分:1)
经过几次误解后,我终于得到了你所需要的东西:)
SELECT cnt_range * 2 AS days_range,
CASE WHEN SUM(trans_cnt) > 0 THEN
SUM(trans_sum) / SUM(trans_cnt)
ELSE 0
END AS average_amount
FROM (
SELECT SUM(amount) AS trans_sum,
COUNT(*) AS trans_cnt,
FLOOR(COUNT(*) / 2) AS cnt_range
FROM transactions
GROUP BY
TO_DATE(created)
) ao
GROUP BY
cnt_range
答案 1 :(得分:1)
这是一个尝试(但没有经过测试):
SELECT CASE WHEN txn_per_day BETWEEN 0 AND 2 THEN 2
WHEN txn_per_day BETWEEN 2 AND 4 THEN 4
WHEN txn_per_day BETWEEN 4 AND 6 THEN 6
ELSE 8 -- or more
END CASE AS num_txns, AVG(t3.amount)
FROM (
SELECT t1.*, COUNT(*) AS txn_per_day
FROM transactions t1 JOIN transactions t2
ON (TO_DAYS(t1.created) = TO_DAYS(t2.created))
GROUP BY t1.id
) t3
GROUP BY num_txns;
这不是特别快。生成报告是可以的,但是如果你需要它在PHP请求期间运行,那就不太好了。
答案 2 :(得分:1)
SELECT AVG(`num`), ((`num` - 1) DIV 2) * 2 AS `tier`
FROM (
SELECT DATE_FORMAT(`created`, '%Y-%m-%d') AS `day`, COUNT(*) AS `num`
FROM `yourtable`
GROUP BY 1
) AS `src`
GROUP BY `tier`
答案 3 :(得分:-1)
尝试类似
的内容SELECT AVG(`amount`) as `amount`,
DATE_FORMAT(`created`, '%Y-%m-%d') as `date`
FROM `transactions`
GROUP BY DATE_FORMAT(`created`, '%Y-%m-%d')
在Date-and-time functions处查看更多内容,并查看BETWEEN function