【问题标题】:SQL don't show duplicates/only show last value [duplicate]SQL 不显示重复项/仅显示最后一个值 [重复]
【发布时间】:2020-12-29 04:18:48
【问题描述】:

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

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 是客户购买商品的次数。现在的问题是我不需要他们过去购买的价值,而只需要最后/当前的余额。 那么如何指定我只需要每个客户的最后一个值呢?

【问题讨论】:

    标签: mysql sql subquery greatest-n-per-group window-functions


    【解决方案1】:

    如果您运行的是 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-29
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多