我有这样的查询:
SELECT cus_id, ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance, date_added
FROM `customer_wallet`
GROUP BY cus_id
它将获得客户的平衡(独特的客户)。我希望修改这个,如果余额是减去那么它会来,我想要最新的日期(date_added
)。
我试过这样做:
SELECT cus_id, ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance, date_added
FROM `customer_wallet`
GROUP BY cus_id
ORDER BY date_added
但是,它在获得所有结果后给出了分类记录。我想要个人客户的最新记录。
如果您需要更多信息或架构,请与我们联系。 感谢。
我也可以在php
中检查负余额的记录。但是,如果我能在查询中做到这一点,那就太棒了。
答案 0 :(得分:1)
您需要使用聚合函数来选择最近的日期 - 我相信默认情况下mysql只为该列选择一个随机值。
SELECT cus_id,
ROUND(SUM(credit_in)-SUM(credit_out), 2) as balance,
max(date_added) as most_recent
FROM `customer_wallet`
Having SUM(credit_in) < SUM(credit_out)
GROUP BY cus_id