简体   繁体   中英

select from 2 table based on count of 3rd table

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,
       COU­NT(distinct reimbursement.reimbu­rse_id) as nor,
       SUM(distinct reimbursement.reimbu­rse_total)
FROM member INNER JOIN
     reimbursement 
     ON member.member_id = reim­bursement.member_id INNER JOIN
     receipt
     ON reimbursement.reimbu­rse_id=receipt.reimb­urse_id
GROUP BY member.memberID

but i got the wrong total.

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 reimbu­rse_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.reimbu­rse_id = rr.reimb­urse_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM