简体   繁体   中英

How to query a nonaggregated column using group by in MySql?

I have a usecase where I want to fetch the latest transaction made by a user on the previous day,
Eg. If today is 26th June 2019,
I want to fetch the last transaction made by the user on 25th June 2019 at 23:59:59

My data is like this -

在此处输入图片说明

I'm not good at SQL and tried the following query -

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

I'm getting the following error -

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

You were close / on the right track. For a given user, you want the highest transaction ID for that user LESS than the given created date in question. Once you have that, then grab the full detail line from transactions table.

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

We can join on the maximum transaction ID because it will only ever exist for one user.

You can use ANY_VALUE for the non-aggregated columns. In your case the non-aggregated column was new_balance . So, you could use:

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

More details here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM