我有两张桌子:
'支付'
|id_tax|value|id_currency|
--------------------------
|1 |100 |12 |
|1 |200 |12 |
|1 |300 |13 |
|2 |200 |12 |
|2 |200 |12 |
--------------------------
'速率'
|id_currency|rate|
------------------
|12 |1 |
|13 |6,12|
------------------
这将导致什么SQL查询?
|id_tax|value |
-----------------------------
|1 |100*1+200*1+300*6,12|
|2 |200*1+200*1 |
-----------------------------
答案 0 :(得分:2)
SELECT id_tax, SUM(value * rate)
FROM pay p
JOIN rate r
ON r.id_currency = p.id_currency
GROUP BY
id_tax
答案 1 :(得分:1)
在MySQL中,您可以使用会话变量计算它:
SET @s = 0;
SELECT id_tax, @s := s +(value * rate)
FROM pay p
JOIN rate r
ON r.id_currency = p.id_currency
GROUP BY
p.id_tax
或以纯粹基于集合但效率较低的方式:
SELECT pay.id_currency, pay.val, SUM(pay.value * rate.rate)
FROM pay
JOIN rate
ON rate.id_currency = pay.id_currency
GROUP BY
pay.id_tax