Reputation: 93
I have 3 tables. member reimbursement and receipt. I want to display member's first name,reimbursement total that has a receipt. For example
member
member_id member_name
1 luffy
2 zoro
3 nami
reimbursement
reimburse_id member_id reimburse_total
1 1 5000
2 2 10000
3 3 10000
receipt
receipt_id reimburse_id reimburse_price reimburse_no
1 1 2500 2012232
2 1 2500 2012123
3 2 5000 2012454
4 2 5000 2012565
I want to display all reimbursement of the member which has receipt. In this case the select query should return like this
name No. of reimburse total
luffy 1 5000
zoro 1 10000
nami 0 0
So far this i what i got
SELECT member.member_name,
COUNT(distinct reimbursement.reimburse_id) as nor,
SUM(distinct reimbursement.reimburse_total)
FROM member INNER JOIN
reimbursement
ON member.member_id = reimbursement.member_id INNER JOIN
receipt
ON reimbursement.reimburse_id=receipt.reimburse_id
GROUP BY member.memberID
but i got the wrong total.
Upvotes: 1
Views: 40
Reputation: 1270723
Hmmm. This is a little strange because you are only using receipt
to determine if the values should be used. One method is LEFT JOIN
and some conditional logic:
SELECT m.member_name,
COUNT(rr.reimburse_id) as nor,
SUM(CASE WHEN rr.reimburse_id IS NOT NULL THEN reimburse_total ELSE 0 END) as reimburse_total
FROM member m LEFT JOIN
reimbursement r
ON m.member_id = r.member_id LEFT JOIN
(SELECT DISTINCT rr.reimburse_id
FROM receipt rr
) rr
ON r.reimburse_id = rr.reimburse_id
GROUP BY m.memberID, m.member_name;
The logic behind this query is to use the receipt
table only to determine if a reimbursement is available. The select distinct
removes duplicates. Then the left join
and case
determine if there are matches to the table.
Upvotes: 1