繁体   English   中英

MySql选择最大值的总和

[英]MySql select a sum of the max values

我有三张桌子

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

表2

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

表3

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

我的问题是如何根据id person = 2来获得价格的总和:表3的ref2 =表2的ref2和表2的ref1 =表人的ref1

如果我在表2中有双行,那么我只需要拿最高价格(对于表2的参考10,我只需要拿最高价格50)

结果应该是50 + 10

我希望这是可以理解的

谢谢

您可以在子查询中通过人员ID和ref1列的组合从table3中获取最大值

然后,您可以从这些值中获取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

试试这个...

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM