根据 MA​​X(列名)从多个表中选择和连接行

Selecting and joining rows from multiple tables based on MAX(Column Name)

总的来说,我的目标是从三个表中获取客户的电子邮件、代码和最近的奖励余额。

三个表是:Customer、CustomerCode 和 Rewards

表格大致如下所示...

客户

id   email           lastcode
----|---------------|-----------
000 |test@test.com  | 1234test
001 |test1@test.com | 5678test
002 |test2@test.com | test1234
003 |test3@test.com | test5678

客户代码

id   code      customer
----|---------|---------
100 |1234test | 000
101 |5678test | 001
102 |test1234 | 002
103 |test5678 | 003

奖励

customercode  logdate      balance
-------------|------------|--------
100          | 01/01/2016 | 1200
101          | 04/05/2016 | 40
102          | 06/22/2016 | 130
102          | 10/14/2016 | 220
103          | 12/03/2016 | 500
103          | 01/18/2017 | 750

我正在尝试从链接回客户的所有表中收集信息。我目前正在使用以下 SQL 查询,但 运行 遇到了一些问题。

SELECT Customer.email, Customer.lastcode, CustomerCode.id, Rewards.balance, MAX(Rewards.logdate)
FROM Customer
JOIN CustomerCode ON Customer.lastcode=CustomerCode.code
JOIN Rewards ON CustomerCode.id=Rewards.CustomerCode
GROUP BY Customer.Email, Customer.LastCode, CustomerCode.id, Rewards.Balance

结果

如您所见,我得到了同一客户的多个结果,但我只想获得每个客户的最新奖励余额。

email           lastcode    id    balance    logdate
---------------|-----------|-----|----------|-----------
test@test.com  | 1234test  | 100 | 1200     | 01/01/2016
test1@test.com | 5678test  | 101 | 40       | 04/05/2016
test2@test.com | test1234  | 102 | 130      | 06/22/2016
test2@test.com | test1234  | 102 | 220      | 10/14/2016
test3@test.com | test5678  | 103 | 500      | 12/03/2016
test3@test.com | test5678  | 103 | 750      | 01/18/2017

有什么办法可以去掉那些重复的记录,只显示最近的奖励余额吗?

您可以为此使用相关子查询或聚合:

SELECT c.email, c.lastcode, cc.id, r.balance, r.logdate
FROM Customer c JOIN
     CustomerCode cc
     ON c.lastcode = cc.code JOIN
     Rewards r
     ON cc.id = r.CustomerCode JOIN
     (SELECT r.CustomerCode, MAX(r.logdate) as max_logdate
      FROM Rewards r
      GROUP BY r.CustomerCode
     ) rr
     ON rr.CustomerCode = r.CustomerCode AND rr.max_logdate = r.logdate;

像这样吗?

SELECT
  costumer.email,
  costumer.lastcode,
  reward.costumercode,
  reward.balance
FROM (SELECT DISTINCT
        rewards.costumercode,
        MAX(rewards.balance) as balance
      FROM rewards
      GROUP BY 1) AS reward
JOIN costumercode ON costumercode.id = reward.costumercode
JOIN costumer ON costumer.id = costumercode.costumer

它比 Gordon 的答案更优化,更干净恕我直言。