我有两个表,如下所示:
mysql> select*from receipt;
+----+------------+-------+---------------------+
| id | receipt_id | money | created_at |
+----+------------+-------+---------------------+
| 1 | receipt_3 | 100 | 2018-10-30 00:00:00 |
| 2 | receipt_4 | 200 | 2018-10-29 00:00:00 |
| 3 | receipt_5 | 300 | 2018-10-31 00:00:00 |
+----+------------+-------+---------------------+
3 rows in set (0.00 sec)
mysql> select*from material;
+----+------------+---------------------+
| id | receipt_id | created_at |
+----+------------+---------------------+
| 1 | receipt_3 | 2018-10-30 00:00:00 |
| 2 | receipt_3 | 2018-10-30 00:00:00 |
| 3 | receipt_5 | 2018-10-31 00:00:00 |
+----+------------+---------------------+
3 rows in set (0.00 sec)
我得到的结果是这样的:“从material
的{{1}}内部联接created_at
的{{1}}中选择{sum(money),receipt
。material
。 receipt
= receipt_id
。material
按receipt_id
分组。material
;”
created_at
但是我想通过忽略相同的记录来获得它:
+------------+---------------------+
| sum(money) | created_at |
+------------+---------------------+
| 200 | 2018-10-30 00:00:00 |
| 300 | 2018-10-31 00:00:00 |
+------------+---------------------+
2 rows in set (0.00 sec)
想了很久但没有答案,请帮助,非常感谢。
答案 0 :(得分:2)
只需使用sum(distinct money)
即可:
select sum(distinct money) as sum_money,
m.created_at
from receipt r join material m
on r.receipt_id=m.receipt_id
group by m.created_at;
+------------+---------------------+
| sum_money | created_at |
+------------+---------------------+
| 100 | 2018-10-30 00:00:00 |
| 300 | 2018-10-31 00:00:00 |
+------------+---------------------+
答案 1 :(得分:1)
您可以尝试在子查询中将DISTINCT
用于material
,而忽略与JOIN
相同的记录
SELECT sum(r.money),t1.created_at
FROM (
select DISTINCT receipt_id,created_at
from material
)t1 JOIN receipt r on t1.receipt_id = r.receipt_id
GROUP BY t1.created_at