SQL Join在右表中获取结束日期

问题描述 投票:-1回答:1

我有这样的数据..我希望每个用户都有他们的最后一笔交易,

tb_user

---------------------
userID  |   Name
---------------------
1       |   Alex
2       |   Jack
---------------------

tb_transaction

-------------------------------------
ID  |   userId    |  lastTransaction
-------------------------------------
1   |   1         |  2017-10-10
2   |   1         |  2017-10-11
4   |   2         |  2017-10-8
5   |   2         |  2017-10-15
-------------------------------------

我想得到这样的东西:

Alex -> 2017-10-11  
Jack -> 2017-10-15

我的sql代码是:

select * 
from 
tb_user 
inner join 
(select userID,lastTransaction from tb_transaction order by lastTransaction) as 
x on x.userID = tb_user.userID
mysql sql
1个回答
-1
投票

尝试:

SELECT A.USERID, MAX(B.LASTTRANSACTION) AS LAST_TXN_DATE
FROM
TB_USER A 
LEFT JOIN 
TB_TRANSACTION B
ON A.USERID = B.USERID
GROUP BY A.USERID;

这将为每个用户提供最后一个交易日期。

© www.soinside.com 2019 - 2024. All rights reserved.