问题
I want to compare table 1 and table 2 only once. I want to print the same amount as the wrong amount or the data error on each side.
1.table name : hospital_payment_data
id chart_num chart_name visit card_amount_received
1 9740 t1 2019-01-02 1000
2 23143 t2 2019-01-02 3000
3 14220 t3 2019-01-02 3000
4 2000 t4 2019-01-02 4000
5 3000 t5 2019-01-02 5000
6 3000 t5 2019-01-02 5000
7 4000 t6 2019-01-02 6000
8 5000 t7 2019-01-02 6000
2.table name : credit_card
id card_date advenced_amount
1 2019-01-02 1000
2 2020-01-02 2000
3 2020-01-02 3000
4 2020-01-02 4000
5 2020-01-02 10000
6 2020-01-02 6000
7 2020-01-02 9000
I want Result
in this my query:
SELECT
hospital_payment_data.id,
chart_num,
visit,
chart_name,
sum(card_amount_received) as card_amount_received,
credit_card.card_date,
credit_card.amount as amount,
if(credit_card.amount = sum(card_amount_received), 'ok', 'error') as result
from hospital_payment_data
left join credit_card on date(credit_card.card_date) = visit AND hospital_payment_data.card_amount_received = credit_card.amount
GROUP BY chart_num, visit
in this my wrong result:
Do I have to add or modify the database table to print as I want? Or do I have to add a relationship? All data values available are specified.
回答1:
I think this is what you are after. Let me know if you need something else. You should probably have chart_num in credit_card so you can join the tables together.
Select hpd.chart_num,
hpd.chart_name
hpd.visit,
hpd.card_amount_received,
cc.card_date,
CASE WHEN hpd.card_amount_received = SUM(cc.advenced_amount) THEN hpd.card_amount_received ELSE NULL END AS ‘amount’,
CASE WHEN hpd.card_amount_received > SUM(cc.advenced_amount) THEN ‘error’ ELSE ‘ok’ END AS ‘result’
from hospital_payment_data hpd
LEFT JOIN credit_card ON cc.chart_num=hpd.chart_num AND
date(cc.card_date) = date(hpd.visit)
GROUP BY hpd.chart_num, hpd.visit;
It would probably be a good idea to have a client_visit table in case a client comes to the office twice in a day or sets up a payment plan where they aren’t paying on the day they come to the office.
来源:https://stackoverflow.com/questions/61199435/how-do-i-join-two-tables-and-compare-them-ive-asked-several-times-but-i-coul