I have two tables like shown as below:
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)
I have got the result use this: "select distinct sum(money),material.created_at from receipt inner join material on receipt.receipt_id=material.receipt_id group by 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)
but I want to get this with ignoring same record:
+------------+---------------------+
| sum(money) | created_at |
+------------+---------------------+
| 100 | 2018-10-30 00:00:00 |
| 300 | 2018-10-31 00:00:00 |
+------------+---------------------+
2 rows in set (0.00 sec)
Have thought for a long time but no answer,please help ,thanks a lot.
Just use 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 |
+------------+---------------------+
DB-Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With