I’d like to select a new column named sliced (value can be 1/0 or true/false it doesn’t matter) if area of the current row equals MAX(SUM(c.area)), that is flag the row with highest aggregate value:
SELECT p.name AS name, SUM(c.area) AS area
FROM City AS c
INNER JOIN Province AS p ON c.province_id = p.id
INNER JOIN Region AS r ON p.region_id = r.id
WHERE r.id = ?
GROUP BY p.id
ORDER BY p.name ASC
I’ve tried adding to the selection area = MAX(area) AS sliced or even area = SUM(MAX(c.area)) AS sliced but i’m getting a syntax error. I’ve to admit i’m not so good in SQL. Thank you.
Here’s a way to do it with just one group by:
The inner query (
t1) does the group by and orders by total area largest first.The next query (
t2) gives the first row a value oftruefor columnsliced, all other rowsfalse.The outer query orders the rows in the way you want – by name.
Since there’s only one table scan and group by, this should be very efficient.