I am trying to fetch max column value by grouping other column. I am almost near but stuck at last point. Here is me code
TABLE:
id . sys_id . renewal
1 . aaad00101 . 0
2 . aaad00101 . 1
3 . aaad00104 . 0
4 . aaad00102 . 0
5 . aaad00101 . 2
6 . aaad00103 . 0
SQL Query:
"SELECT * FROM $company WHERE renewal IN (SELECT DISTINCT
MAX(renewal)FROM $company GROUP BY sys_id) ORDER BY sys_id"
Result:
aaad00101-0
aaad00101-2
aaad00102-0
aaad00103-0
aaad00404-0
My code is showing max value with minimum value like top two results. But I want if max value is showing then it should not show minimum value in results.
Let me know what I am missing here. Thanks
Fixed It:
SQL Query:
"SELECT * FROM $company WHERE id IN (SELECT DISTINCT MAX(id)FROM
$company GROUP BY sys_id) ORDER BY sys_id";
Am I correct that you want to keep all the rows you currently have in your table with an additional column that shows the max renewal value for each sys_id?
It's something frequently done in a window function, but since MySQL doesn't currently have that capability you can get around it with an additional join.
SELECT a.*, b.last_renewal FROM company AS a JOIN ( SELECT sys_id, MAX( renewal ) AS last_renewal FROM company GROUP BY sys_id ) AS b USING ( sys_id ) ;
Or are you looking for a renewal value for the latest occurrence, which I assume is for the max value of the id column?
If that's the case, you can concatenate all of the renewal values into a list and order that list by id, and then you can take out the last value in that list.
SELECT sys_id, SUBSTRING_INDEX( GROUP_CONCAT( renewal ORDER BY id ),',',-1 ) AS last_renewal, MAX( id ) AS last_occurance FROM company GROUP BY sys_id ;
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.