简体   繁体   中英

MySQL: Select row order by date with group by

I have mysql query:

SELECT * FROM customer_wallet
WHERE credit_balance<0
GROUP BY cus_id
ORDER BY date_added DESC

It should give me last added detail by means of cus_id with credit_balance<0. But, it's giving me first negative balance one.

It will work if I will remove GROUP BY from my query. But, I need to keep that as all the customers are in same table.

This is SQL Fiddle .

credit_balance should be -50. Not -111.

here is proper query:

SELECT *
FROM customer_wallet as a
inner join
(
  select max(id) as maxid
  from customer_wallet
  WHERE credit_balance<0
  group by cus_id
) as b
on (a.id=b.maxid)

note: this query works because usually data inserted incrementally and we can assume that we can use id instead of date

There are a couple of ways you can do this. For one, try the following:

SELECT cw.*
FROM (
  SELECT *
  FROM customer_wallet 
  WHERE credit_balance < 0
  ORDER BY date_added DESC
) cw
GROUP BY cw.cus_id;

You could also use a MAX() on date_added:

SELECT credit_balance, date_added
FROM customer_wallet
WHERE credit_balance < 0
GROUP BY cus_id
ORDER BY MAX(date_added) DESC;

Either of those should work for you.

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