[英]How to show unique row with corresponding other column max value
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: SQL查询:
"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: SQL查询:
"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? 我是否要保留表格中当前包含的所有行,并另外显示一列,以显示每个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. 这是在窗口函数中经常执行的操作,但是由于MySQL当前不具备此功能,因此您可以通过附加联接来解决它。
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 ) ; 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? 还是您正在寻找最新出现的续订值,我认为这是id列的最大值?
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. 如果是这样,您可以将所有续订值连接到一个列表中,并按ID对该列表进行排序,然后可以取出该列表中的最后一个值。
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 ; SELECT sys_id,SUBSTRING_INDEX(GROUP_CONCAT(renewal ORDER BY id),',',-1)AS last_renewal,MAX(id)AS last_occurance from公司GROUP BY sys_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.