GROUP_BY,MAX()和only_full_group_by

时间:2016-11-11 17:55:24

标签: mysql sql group-by

我有一张桌子:

ID  ACCOUNT  BALANCE  TIME
1   Bill     10       1478885000
2   Bill     10       1478885001
3   James    5        1478885002
4   Ann      20       1478885003
5   Ann      15       1478885004

我希望获得多个帐户的最新(基于TIME)余额。即:

ACCOUNT  BALANCE
Bill     10
Ann      15

我尝试使用这个SQL:

SELECT ACCOUNT, BALANCE, max(TIME)
FROM T1
WHERE ACCOUNT IN ( 'Bill', 'Ann')
GROUP BY ACCOUNT

我收到错误:

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'BALANCE' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我理解错误并尝试了不同的SQL,但仍然不了解如何在没有多个查询的情况下检索所需的数据。

P.S。我使用MySQl 5.7

3 个答案:

答案 0 :(得分:2)

itemA, itemB = "a", "b"

编辑:多次更改时更好地使用变量

SQL DEMO: 我将SELECT T1.ACCOUNT, T1.BALANCE, T1.TIME FROM T1 JOIN (SELECT ACCOUNT, max(TIME) as m_time FROM T1 WHERE T1.ACCOUNT IN ( 'Bill', 'Ann') GROUP BY ACCOUNT ) T2 ON T1.ACCOUNT = T2.ACCOUNT AND T1.TIME = T2.m_time WHERE T1.ACCOUNT IN ( 'Bill', 'Ann') 的日期更改为相同

Ann

<强>输出

SELECT ACCOUNT, BALANCE, TIME
FROM (
      SELECT ACCOUNT, BALANCE, TIME, 
             @rn := if(ACCOUNT = @acc, 
                       @rn + 1, 
                       if(@acc := ACCOUNT, 1, 1) as rn                 
      FROM T1, (SELECT @rn := 0, @acc:= '') P
      WHERE ACCOUNT IN ( 'Bill', 'Ann')
      ORDER BY ACCOUNT, TIME desc, BALANCE desc
     ) T
WHERE T.rn = 1

答案 1 :(得分:0)

您的选择中的列不在

组中

或者您添加的所有列都不在聚合函数

SELECT ACCOUNT, BALANCE, max(TIME)
FROM T1
WHERE ACCOUNT IN ( 'Bill', 'Ann')
GROUP BY ACCOUNT, BALANCE 

或者您使用

更改sql_mode
 SET sql_mode = ''

  SELECT ACCOUNT, BALANCE, TIME
  FROM T1
  where id  In (
            select id from T1 where (account, time ) in (
                        select account, max(time) 
                        from t1  
                        WHERE ACCOUNT IN ( 'Bill', 'Ann') group by account))

答案 2 :(得分:0)

错误很明显。如果您想要每个帐户的最新余额,可以采用以下方式:

select t1.*
from t1
where t1.time = (select max(tt1.time) from t1 tt1 where t1.account = tt1.account);

您可以在外部查询中添加where以过滤特定帐户。