如何合并表和总和

时间:2013-10-25 20:38:21

标签: mysql sql

我有两张表格,其中包含一些特定数据:

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
编辑:忘了添加简,他从来没有捐过。

我怎么能这样做?

3 个答案:

答案 0 :(得分: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包含唯一值,您可以将该组保留为u.id,如果不是,那么您必须按u.id, u.username进行分组。

小提琴here

答案 1 :(得分: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

答案 2 :(得分:0)

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

中的月份匹配

CURDATE()MONTH()

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