簡體   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