[英]MySql select a sum of the max values
I have three tables 我有三张桌子
person 人
----+-------
id | ref1 |
----+-------
2 | 10 |
----+-------
2 | 11 |
----+-------
3 | 12 |
----+-------
Table 2 表2
+-------+-------
|ref1 | ref2 |
-------+--------
|10 | 20 |
--------+-------
|10 | 22 |
--------+-------
|11 | 35 |
--------+-------
|26 |47 |
Table 3 表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 我的问题是如何根据id person = 2来获得价格的总和:表3的ref2 =表2的ref2和表2的ref1 =表人的ref1
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 ) 如果我在表2中有双行,那么我只需要拿最高价格(对于表2的参考10,我只需要拿最高价格50)
the result should be 50+10 结果应该是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 您可以在子查询中通过人员ID和ref1列的组合从table3中获取最大值
You can then get the maximum
out of these values 然后,您可以从这些值中获取maximum
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.