开发者

Select with grouping in MySQL

开发者 https://www.devze.com 2023-02-20 13:16 出处:网络
I have 2 tables : \'pay\' id_tax|value|id_currency| -------------------------- |1|100|12| |1|200|12| |1|300|13|

I have 2 tables :

'pay'

|id_tax|value|id_currency|
--------------------------
|1     |100  |12         |
|1     |200  |12         |
|1     |300  |13         |
|2     |200  |12         |
|2     |200  |12         |
--------------------------

'rate'

|id_currency|rate|
------------------
|12         |1   |
|13         |6,12|
------------------
开发者_开发问答

What SQL query will result in this?

|id_tax|value               |
-----------------------------
|1     |100*1+200*1+300*6,12|
|2     |200*1+200*1         |
-----------------------------


SELECT  id_tax, SUM(value * rate)
FROM    pay p
JOIN    rate r
ON      r.id_currency = p.id_currency
GROUP BY
        id_tax


In MySQL, you can calculate it using session variables:

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

or in a pure set-based but less efficient way:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消