gpt4 book ai didi

mysql - 对两行求和并按日期/总计排序

转载 作者:太空宇宙 更新时间:2023-11-03 12:21:42 25 4
gpt4 key购买 nike

需要一些帮助来构建查询,这是我目前的方案:

users:
+----+------------+
| id | username |
+----+------------+
| 1 | rob |
| 2 | john |
| 3 | jane | <--- jane never has donated
| 4 | mike |
+----+------------+

donations:
+--------------------+------------+
| uid | amount | date |
+---------+----------+------------+
| 1 | 20 | 2013-10-10 |
| 2 | 5 | 2013-10-03 |
| 2 | 50 | 2013-09-25 |
| 2 | 5 | 2013-10-01 |
| 4 | 100 | 2012-10-01 | <-- past year
+---------+----------+------------+


Result I want:
+---------+-------------+---------+-------------+---------------+----------+
| id | username | amount | monthly | totalamount | total |
+---------+-------------+---------+-------------+ --------------+----------+
| 1 | rob | 20 | 1 | 20 | 1 |
| 2 | john | 60 | 3 | 60 | 3 |
| 3 | jane | 0 | 0 | 0 | 0 |
| 4 | mike | 0 | 0 | 100 | 1 |
+---------+-------------+-----------------------+---------------+----------+

这是我的查询:

SELECT
u.*,
COALESCE(sum(d.amount), 0) amount,
COUNT(d.uid) monthly,
COUNT(d.amount) as Total, <-- need to get sum all time donations and number of times donated
FROM users u
LEFT JOIN donations d
ON u.id = d.uid
AND (month(d.date), year(d.date)) = (month(CURDATE()), year(CURDATE()))
GROUP BY u.id ORDER BY u.id ASC

所以我需要从相同的数据中添加 2 个不同的总和。

编辑:http://sqlfiddle.com/#!2/20a974/9架构和数据

我该怎么做?

最佳答案

为此,我们需要在 select 而不是 join 上过滤数据。

删除此条件:

AND (month(d.date), year(d.date)) = (month(CURDATE()), year(CURDATE()))

并将其添加到选择中:

SUM (CASE WHEN (month(d.date), year(d.date)) = (month(CURDATE()), year(CURDATE())) THEN 1 ELSE 0 END) as monthly

编辑:

整个查询:

SELECT users.id, users.username, 
COALESCE(sum(CASE WHEN (month(donations.date), year(donations.date)) = (month(CURDATE()), year(CURDATE())) THEN donations.amount ELSE 0 END), 0) monthly_sum,
COALESCE(sum(CASE WHEN (month(donations.date), year(donations.date)) = (month(CURDATE()), year(CURDATE())) THEN 1 ELSE 0 END), 0) monthly_amount,

COALESCE(sum(donations.amount), 0) total_sum,
count(*) total_amount

from users
left join donations
on donations.uid = users.id
group by users.id, users.username

http://sqlfiddle.com/#!2/20a974/20/0

关于mysql - 对两行求和并按日期/总计排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com