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
我有两张桌子的代金券和订单。我想要
select sum(value)
from vouchers with distinct orderid
group by ordertouserId
我不确定我该怎么做。
这个查询:
select o.ordertouserId, count(o.order_id) as Orders, sum(v.value) as Total_value
from vouchers v
join orders o on o.voucher_id = v.voucher_id
group by o.ordertouserId
给出结果:
ordertouserId Orders Total_value
1 3 500
2 2 1000
但我想选择sum(v.value)
对应的distinct o.orderId
as Total_value
。
期望的结果:
ordertouserId Orders Total_value
1 3 500
2 1 500