-3

我有两个包含一些特定数据的表:

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

donations:
+--------------------+------------+
|   uid   |  amount  |   date     |
+---------+----------+------------+
|    1    |    20    | 2013-10-10 | 
|    2    |    5     | 2013-10-03 | 
|    2    |    50    | 2013-09-25 |
|    2    |    5     | 2013-10-01 |
+---------+----------+------------+


Result I want:
+---------+-------------+---------+-------------+
|    id   |   username  | amount  |   monthly   | <- sum of donations this month
+---------+-------------+---------+-------------+
|    1    |     rob     |   20    |      1      |
|    2    |     john    |   60    |      3      |
|    3    |     jane    |   0     |      0      | <- jane added
+---------+-------------+-----------------------+

这是我的查询:

SELECT t1.*, sum(t2.amount) amount, count(*) as monthly
FROM users t1
inner join donations t2
  on t2.uid = t1.id
group by t1.username

编辑:忘记添加简,他从未捐赠过。

我怎么能做到这一点?

4

3 回答 3

1

您的输出是错误的,因为您没有在结果中过滤掉 9 月的记录(应仅考虑 2013 年 10 月)。

您的预期输出应该是这样的:

| ID | USERNAME | AMOUNT | MONTHLY |
|----|----------|--------|---------|
|  1 |      rob |     20 |       1 |
|  2 |     john |     10 |       2 |
|  3 |     jane |      0 |       0 |

获取输出的查询是:

SELECT
  u.id,
  u.username,
  COALESCE(sum(d.amount), 0) amount,
  COUNT(d.uid) monthly
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

假设users.ID拥有唯一值,您可以离开 group by ,就u.id好像它不是那样,那么您将不得不 group by u.id, u.username

在这里拉小提琴。

于 2013-10-25T21:06:16.327 回答
0
SELECT t1.*, sum(t2.amount) as amount, count(t2.amount,t2.`date`) as monthly
FROM users t1
inner join donations t2
  on t2.uid = t1.id
where month(t2.`date`)=month(curdate()) and year(t2.`date`)=year(curdate())
group by t1.username
于 2013-10-25T20:44:55.853 回答
0

如何使用当前日期并提取月份并与列中的月份匹配date

CURDATE() ,月()

SELECT t1.*, (CASE WHEN SUM(t2.amount) IS NULL THEN 0 ELSE SUM(t2.amount) END) amount,
count(*) as monthly
FROM users t1
left join donations t2
  on t2.uid = t1.id
WHERE  MONTH(t2.`date`)=MONTH(CURDATE()) AND  YEAR(t2.`date`)=YEAR(CURDATE())
group by t1.id
于 2013-10-25T20:45:02.520 回答