根据列的最大值从表中提取所有数据,并将其分组到另一列

时间:2018-05-02 10:40:17

标签: mysql ruby-on-rails group-by

我有一个名为Policy的表,如:

Name     Version Id
Policy1  1.0.0   1
Policy2  2.0.0   2
Policy1  1.1.1   3
Policy2  2.0.1   4

我尝试提取以下内容:

Name     Version Id
Policy1  1.1.1   3
Policy2  2.0.1   4

基于每个名称的一个值和表格中的最高版本。

我尝试了以下内容:

ActiveRecord::Base.connection.exec_query('(SELECT MAX(A.version) AS rev, A.name FROM policies A GROUP BY A.name) ')

如果我将id添加到混音中,例如:

ActiveRecord::Base.connection.exec_query('(SELECT MAX(A.version) AS rev, A.name, A.id FROM policies A GROUP BY A.name) ')

我收到错误:

ActiveRecord::StatementInvalid: Mysql2::Error: Expression #3 of SELECT             
list is not in GROUP BY clause and contains nonaggregated column     
'pikto_dev.A.id' which is not functionally dependent on columns in 
GROUP BY clause; this is incompatible with 
sql_mode=only_full_group_by: (SELECT MAX(A.version) AS rev, A.name, 
A.id FROM policies A GROUP BY A.name)`

我也尝试过这样的事情:

Policy.select(:id, "MAX(version)", :name).group(:name)

1 个答案:

答案 0 :(得分:2)

如果您也想要id,则应将聚合结果与原始表

一起加入
select t1.rev, t1.name, p.id  
from (
   SELECT MAX(A.version) AS rev, A.name
  FROM policies A 
   GROUP BY A.name ) t1
inner join  policies p on p.version = t1.rev and t1.name = p.name