mysql - Select one value of column, corresponding with distinct value of other column -


voucherid   value  balance    1         100    20    2         300    120    3         500    220  orderid   voucherid  ordertouserid    1         1           1    2         3           2       3         2           1    4         1           1      2         2           2    

i have 2 tables vouchers , orders. want to

select sum(value) vouchers distinct orderid group ordertouserid 

i'm not sure how can this.

this query:

select o.ordertouserid, count(o.order_id) orders, sum(v.value) total_value vouchers v join orders o on o.voucher_id = v.voucher_id group o.ordertouserid 

gives result:

ordertouserid  orders total_value  1               3      500     2               2      1000 

but want select sum(v.value) corresponding distinct o.orderid total_value.

desired result:

ordertouserid  orders total_value  1               3      500     2               1      500 

in desired output, ordertouserid = 2 shows total_value voucherid = 3. how did determine don't want show total_value voucherid = 2?

sorry, that's not answer, don't have enough "reputation" post comment on question. baring better understanding of how selected total_value = 500 (rather total_value = 300) ordertouserid = 2, answer have be:

the output desire not possible obtain because there no clear way determine voucherid should used in calculating total_value ordertouserid = 2.

btw, think there's error in first output table shows ordertouserid = 2 total_value = 1000. shouldn't totalvalue ordertouserid = 2 300 + 500 = 800?