Py学习  »  DATABASE

如何在mysql中使用group by查询未聚合的列?

Aniruddha Raje • 7 年前 • 2234 次点击  

我有一个用例,想获取用户前一天所做的最新交易,
如果今天是2019年6月26日,
我想去拿 the last transaction made by the user on 25th June 2019 at 23:59:59

我的数据是这样的-

enter image description here

我不擅长sql并尝试了以下查询-

SELECT MAX(transaction_id), user_id, MAX(created_date), new_balance  
FROM transaction
where created_date < 1561507199 
GROUP BY user_id;

我得到以下错误-

Error Code: 1055. Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'transaction.new_balance' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47476
文章 [ 1 ]  |  最新文章 7 年前
DRapp
Reply   •   1 楼
DRapp    7 年前

你走得很近[在正确的轨道上]。对于给定的用户,您希望该用户的最高事务id小于给定的创建日期。一旦有了它,就从transactions表中获取完整的细节行。

select
      T2.*
   from
      ( select user_id, max( transaction_id ) maxTransID
           from transaction
           where created_date < 1561507199
           group by user_id ) Tmp
         JOIN Transaction T2
            on Tmp.MaxTransID = T2.Transaction_ID

我们可以加入最大事务ID,因为它只存在于一个用户。