I need some help with a problem. I am trying to get a max from a sum with three tables. I've been trying to figure it out with help from other post on here but so far none of them have helped me. I manage to get the right answer when using limit 1 but i was wondering how I can do it without that.
The three tables are
So far I got this
(select vnamn, sum(mangd) as a from land, export, varldsdel where varldsdel.vkod=land.vkod and land.landkod=export.landkod and ar=2004 group by vnamn)
this give me the following result
+----------------+-------------+
| vnamn | sum(mangd) |
+----------------+-------------+
| sydamerika | 61000 |
| noramerika | 50000 |
| europa | 1200 |
+----------------+-------------+
Now this is where I get stuck. I want to do a max of this result so that only "sydamerika | 61000" shows and I've been trying to do this all day but can't get the hang of it.
Thanks
since you already have the select query, you can do this instead;
Select vnamn, max(a) as mangd from (select vnamn, sum(mangd) as a from land, export, varldsdel where varldsdel.vkod=land.vkod and land.landkod=export.landkod and ar=2004 group by vnamn) k
You can use a Common Table Expression
(CTE) and then filter out on the highest value using the MAX
aggregation function:
WITH summed_mangd AS (
SELECT vnamn,
SUM(mangd) AS total
FROM land
INNER JOIN export
ON export.landkod = land.landkod
INNER JOIN varldsdel
ON varldsdel.vkod = land.vkod
WHERE ar = 2004
GROUP BY vnamn
)
SELECT vnamn,
total
FROM summed_mangd
WHERE total = (SELECT MAX(total)
FROM summed_mangd)
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.