简体   繁体   中英

MySql select a sum of the max values

I have three tables

person

----+-------
id  | ref1 |
----+-------
 2  | 10   |
----+-------
 2  | 11   |
----+-------
 3  | 12   |
----+-------

Table 2

+-------+-------
|ref1   | ref2 |
-------+--------
|10     | 20   |
--------+-------
|10     | 22   |
--------+-------
|11     | 35   |
--------+-------
|26     |47    |

Table 3

-----+------
ref2 |price|
-----+------
20   |50   |
-----+------
22   |5    |
-----+-----
35   |10   |

My question is how can i get the sum of prices according to : ref2 of table3 = ref2 of table2 and ref1 of table2 = ref1 of table person when id person = 2

Fot that i need to take only the max price if i have double row in table 2 (for the ref 10 of table 2 i need to take the only the price 50 )

the result should be 50+10

I hope that this is understandable

And thanks

You can get maximum value from table3 per combination of person id and ref1 column in a subquery

You can then get the maximum out of these values

select t.id, max(refPrice) as maxPrice
from 
(
select p.id , p.ref1 + max(t3.price) as refPrice
from person p
join table2 t2
on p.ref1 = t2.ref1
join table3 t3
on t2.ref2 = t3.ref2
group by p.id, p.ref1
  )t
group by t.id

Try this way...

SELECT SUM(GroupSum) as
   TotalSum
FROM(
   SELECT MAX(t3.price) as GroupSum FROM Person p 
   INNER JOIN Table2 t2 ON p.ref1=t2.ref1
   INNER JOIN Table3 t3 ON
   t2.ref2=t3.ref2 WHERE p.id=2
   GROUP BY p.id,p.ref1
   ) ttl
GROUP BY t.id

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