RNK
RNK

Reputation: 5792

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.

Upvotes: 0

Views: 47

Answers (2)

gmiley
gmiley

Reputation: 6604

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.

Upvotes: 0

Iłya Bursov
Iłya Bursov

Reputation: 24146

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

Upvotes: 1

Related Questions