MySQL最大值在行中

时间:2016-01-24 04:31:59

标签: mysql sql greatest-n-per-group

我遇到了MySQL查询的问题,这是" Id的变体,对于具有最大值"的行。我要么在所有试验中得到错误或结果不正确。

这是表结构

Row_id
Group_id
Grp_col1
Grp_col2
Field_for_aggregate_func
Another_field_for_row

对于具有特定group_id的所有行,我想按字段Grp_col1,Grp_col2分组,然后获取Field_for_aggregate_func的最大值,然后获得Another_field_for_row的相应值。

我试过的查询就像下面的

SELECT c.*
FROM mytable as c left outer join mytable as c1
on (
    c.group_id=c1.group_id and
    c.Grp_col1 = c1.Grp_col1 and
    c.Grp_col2 = c1.Grp_col2 and
    c.Field_for_aggregate_func > c1.Field_for_aggregate_func
)
where c.group_id=2

在这个问题的替代解决方案中,我想要一个高性能解决方案,因为它将用于大量数据。

编辑:以下是行和预期答案的示例集

Group_ID Grp_col1 Grp_col2  Field_for_aggregate_func Another_field_for_row  
2           --      N       12/31/2015               35 
2           --      N       1/31/2016                15 select 15 from group for max value 1/31/2016

2           --      Y       12/31/2015               5  
2           --      Y       1/1/2016                 15 
2           --      Y       1/2/2016                 25 
2           --      Y       1/3/2016                 30 select 30 from group for max value 1/3/2016

2 个答案:

答案 0 :(得分:1)

您可以使用子查询查找最大值,然后将其与原始表连接起来:

select m1.group_id, m1.grp_col1, m1.grp_col2, m1.another_field_for_row, max_value
from mytable m1, (
  select group_id, grp_col1, grp_col2, max(field_for_aggregate_func) as max_value
  from mytable
  group by group_id, grp_col1, grp_col2) as m2
where m1.group_id=m2.group_id
  and m1.grp_col1=m2.grp_col1
  and m1.grp_col2=m2.grp_col2
  and m1.field_for_aggregate_func=m2.max_value;

注意给定分组的max_value不止一个。您将为该分组获取多行。 Fiddle here.

答案 1 :(得分:0)

试试这个。

请参阅此处的小提琴演示

http://sqlfiddle.com/#!9/9a3c26/8

Select t1.* from table1 t1 inner join
(
Select a.group_id,a.grp_col2,
A.Field_for_aggregate_func, 
count(*) as rnum from table1 a
Inner join table1 b
On a.group_id=b.group_id
And a.grp_col2=b.grp_col2
And a.Field_for_aggregate_func
<=b.Field_for_aggregate_func
Group by a.group_id,
a.grp_col2,
a.Field_for_aggregate_func) t2
On t1.group_id=t2.group_id
And t1.grp_col2=t2.grp_col2
And t1.Field_for_aggregate_func
=t2.Field_for_aggregate_func
And t2.rnum=1

首先,我根据日期按降序分配rownumber。选择该日期的所有记录。