我有mysql查询:
SELECT * FROM customer_wallet
WHERE credit_balance<0
GROUP BY cus_id
ORDER BY date_added DESC
它应该通过带有credit_balance&lt; 0的cus_id给我最后添加的细节。但是,它给了我第一个负余额。
如果我从查询中删除GROUP BY
,它将会有效。但是,我需要保持这一点,因为所有客户都在同一张桌子里。
这是SQL Fiddle。
credit_balance应为-50。不是-111。
答案 0 :(得分:1)
这是正确的查询:
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)
注意:此查询有效,因为通常会逐步插入数据,我们可以假设我们可以使用id而不是date
答案 1 :(得分:0)
有几种方法可以做到这一点。例如,尝试以下方法:
SELECT cw.*
FROM (
SELECT *
FROM customer_wallet
WHERE credit_balance < 0
ORDER BY date_added DESC
) cw
GROUP BY cw.cus_id;
你也可以在date_added:
上使用MAX()SELECT credit_balance, date_added
FROM customer_wallet
WHERE credit_balance < 0
GROUP BY cus_id
ORDER BY MAX(date_added) DESC;
其中任何一个都适合你。