MySQL:max()和group by - 错误值的问题

时间:2010-07-14 15:51:46

标签: mysql greatest-n-per-group

我的SQL语句有问题: 使用这个

select a.id as ID, a.dur as DUR, DATE(FROM_UNIXTIME(timestampCol)) as date, 
 a_au.re as RE, a_au.stat as STAT from b_c
  inner join c on b_c.c_id = c.id
  inner join a on c.id = a.c_id
  inner join a_au on a.id = a_au.id
  inner join revi on a_au.rev = revi.rev
  where b_c.b_id = 5

我得到了这个结果:

ID  DUR         date   RE  STAT
-------------------------------
31, 10, '2010-07-14', 2200, 0
31, 10, '2010-07-14', 2205, 0
31, 10, '2010-07-14', 2206, 2
31, 10, '2010-07-14', 2207, 0
31, 10, '2010-07-14', 2210, 2
31, 10, '2010-07-15', 2211, 0
31, 10, '2010-07-14', 2213, 1
32, 10, '2010-07-14', 2203, 0
32, 10, '2010-07-14', 2204, 0
32, 10, '2010-07-14', 2208, 2
32, 10, '2010-07-14', 2209, 0
32, 10, '2010-07-15', 2212, 2

现在我想为一个ID和日期组合获得一个结果行。另外,我想获得具有最高RE编号的结果行。

所以我写下我的陈述:

select a.id as ID, a.dur as DUR, DATE(FROM_UNIXTIME(timestampCol)) as date, 
 max(a_au.re) as RE, a_au.stat as STAT from b_c
  inner join c on b_c.c_id = c.id
  inner join a on c.id = a.c_id
  inner join a_au on a.id = a_au.id
  inner join revi on a_au.rev = revi.rev
  where b_c.b_id = 5
  group by ID, date

现在我得到了这个结果:

ID  DUR         date   RE  STAT
-------------------------------
31, 10, '2010-07-14', 2213, 0
31, 10, '2010-07-15', 2211, 0
32, 10, '2010-07-14', 2209, 0
32, 10, '2010-07-15', 2212, 2

一切似乎都没问题,我每天有一个结果行/ ID组合和RE编号最高的行。但是:列STAT没有正确的值! 行

31, 10, '2010-07-14', 2213, 0

必须具有状态1:

31, 10, '2010-07-14', 2213, 1

所以我的陈述中一定有错误。似乎MySQL获取它找到的第一个STAT列值。但是我希望有相应的一个。

我该怎么办? 我在这里看到了关于此的其他主题: Selecting all corresponding fields using MAX and GROUP BY 但我无法将其转移到我的SQL语句中。

提前多多感谢&最诚挚的问候。

1 个答案:

答案 0 :(得分:1)

使用:

SELECT a.id as ID, 
       a.dur as DUR, 
       DATE(FROM_UNIXTIME(timestampCol)) as date, 
       a_au.re as RE, 
       a_au.stat as STAT 
 FROM b_c
 JOIN c on b_c.c_id = c.id
 JOIN a on c.id = a.c_id
 JOIN a_au on a.id = a_au.id
 JOIN revi on a_au.rev = revi.rev
 JOIN ( SELECT a.id as ID, 
               DATE(FROM_UNIXTIME(timestampCol)) as date, 
               MAX(a_au.re) as Max_RE
          FROM b_c
          JOIN c on b_c.c_id = c.id
          JOIN a on c.id = a.c_id
          JOIN a_au on a.id = a_au.id
          JOIN revi on a_au.rev = revi.rev
         WHERE b_c.b_id = 5 
      GROUP BY a.id, DATE(FROM_UNIXTIME(timestampCol))) x ON x.id = a.id
                                                         AND x.date = DATE(FROM_UNIXTIME(timestampCol))
                                                         AND x.max_re = a_au.re
WHERE b_c.b_id = 5 

可悲的是,MySQL不支持WITH子句,这可能使这更容易阅读。