简体   繁体   中英

Issue while using inner join with sum

I have two (2) tables: ps_wk_mp_seller_transaction_history

在此处输入图片说明 And ps_wk_mp_seller_order_status

在此处输入图片说明

I want to totalize seller_amount only if current_state = 5

For that I have written this:

select sum(seller_amount) as seller_amount
from ps_wk_mp_seller_transaction_history th inner join 
     ps_wk_mp_seller_order_status os
     on os.id_order = th.id_transaction and
        os.current_state = 5 and
        th.id_customer_seller = 2;

For id_customer_seller=2 I get this 4984.020000 (4950+34.02) and it is exact

But I get 25.848000 instead of NULL for id_customer_seller=5

Can someone help me?

May be you can test yourself, this the code: https://github.com/kulturman/fakerepo

First of all your records have some logic issue, id_transaction have tow transactions with same id_transaction but different amount and different state ! so transaction with id 41 having state 5 and that why customer 5 will not be null because 41 is in state 5.

To fix this

transaction id must be unique id for every transaction in order to differentiate between transaction state and amount

the query should be like this

select sum(seller_amount) as seller_amount
from ps_wk_mp_seller_transaction_history th 
left join ps_wk_mp_seller_order_status os 
  on os.id_order=th.id_transaction
where 
  th.id_customer_seller = 2
  and  os.current_state=5 

working example here

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