[英]Selecting and joining rows from multiple tables based on MAX(Column Name)
總體而言,我的目標是從三個表中獲取客戶的電子郵件,代碼和最近的獎勵余額。
這三個表是:客戶,客戶代碼和獎勵
這些表大致如下所示...
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的anwser更優化,並且更干凈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.