SQL 不显示 duplicates/only 显示最后一个值

SQL don't show duplicates/only show last value

这是我获取一些客户数据及其余额的查询

SELECT c.id, a.fk_cust, c.firstname, c.lastname, t.cust_count, t.cust_balance
FROM addr a
INNER JOIN cust c ON a.fk_cust = c.id
INNER JOIN trans t ON c.id = t.fk_cust
WHERE c.id = t.fk_cust
ORDER BY lastname ASC

输出示例:

id fk_cust firstname lastname   cust_count cust_balance
1     1    test      customer1  1          0.32
1     1    test      customer1  2          0.64
2     2    test      customer2  1          0.74
3     3    test      customer3  1          0.23
3     3    test      customer3  2          0.56

我希望输出的样子>

id fk_cust firstname lastname   cust_count cust_balance
1     1    test      customer1  2          0.64
2     2    test      customer2  1          0.74
3     3    test      customer3  2          0.56

cust_count是客户购买东西的次数。现在问题是我不需要他们过去购买的价值,只需要 last/current 余额。 那么我如何指定我只想要每个客户的最后一个值?

如果您是 运行 MySQL 8.0,您可以通过在子查询中降序排列 cust_count 每个客户的交易,然后使用该信息仅保留最新交易:

SELECT c.id, a.fk_cust, c.firstname, c.lastname, t.cust_count, t.cust_balance
FROM addr a
INNER JOIN cust c ON a.fk_cust = c.id
INNER JOIN (
    SELECT t.*, ROW_NUMBER() OVER(PARTITION BY fk_cust ORDER BY cust_count DESC) rn
    from trans t
) t ON c.id = t.fk_cust
WHERE r.rn = 1
ORDER BY lastname ASC

在早期版本中:

SELECT c.id, a.fk_cust, c.firstname, c.lastname, t.cust_count, t.cust_balance
FROM addr a
INNER JOIN cust c ON a.fk_cust = c.id
INNER JOIN trans t ON c.id = t.fk_cust AND r.rn = 1
WHERE t.cust_count = (SELECT MAX(t1.cust_count) FROM trans t1 WHERE t1.fk_cust = c.id)
ORDER BY lastname ASC