我的两个表如下:
Table 1 : Transaction
TRANS_ID (primary key), TRANS_DATE, TRANS_STATUS, USER_ID (Foreign_Key)
状态更改时将重复相同的user_id
Table 2 : Users
USER_ID (Primary_Key), USER_NAME, USER_DOB, OTHER_INFO
我想获取用户信息以及上次交易状态。
我熟悉以下查询。
SELECT MAX(Transaction.TRANS_DATE),Transaction.TRANS_STATUS, Users.USER_NAME, Users.USER_DOB
FROM Users
INNER_JOIN Transaction ON Transaction.USER_ID = Users.USER_ID
WHERE Transaction.USER_ID = @UserID
我将UserID
与Parameter.AddWithValue
一起传递。不幸的是,此方法不会为TRANS_STATUS
返回MAX(TRANS_DATE)
。它确实返回MAX(TRANS_DATE)
,但是TRANS_STATUS
是第一个出现的记录,而不是与STATUS
记录相对应的MAX(TRANS_DATE)
。
请让我知道如何获得TRANS_STATUS
的{{1}}。我更喜欢使用MAX(TRANS_DATE)
,但建议值得赞赏。
我仍然无法上班。
这是我的表脚本。
INNER JOIN
答案 0 :(得分:0)
您可以在子查询上使用连接,最长为TRANS_DATE
select t.max_trans, t.USER_NAME, t.USER_DOB
from Transaction
INNER JOIN
(
SELECT MAX(Transaction.TRANS_DATE) max_trans,
Transaction.USER_ID, Users.USER_NAME, Users.USER_DOB
FROM Users
INNER_JOIN Transaction ON Transaction.USER_ID = Users.USER_ID
WHERE Transaction.USER_ID = @UserID
) t on Transaction.USER_ID = t.USER_ID and t.max_trans = Transaction.TRANS_DATE
答案 1 :(得分:0)
如果我理解正确,这可能对您有用
SELECT A.USER_ID AS USER_ID, A.TRANS_DATE AS TRANS_DATE, TRANS_STATUS, USER_NAME, USER_DOB
FROM
(SELECT USER_ID, MAX(TRANS_DATE) AS TRANS_DATE FROM TRANSACTION
GROUP BY USER_ID) A
INNER JOIN
(SELECT USER_ID, TRANS_DATE, TRANS_STATUS FROM TRANSACTION) B
ON A.USER_ID = B.USER_ID
AND A.TRANS_DATE=B.TRANS_DATE
INNER JOIN USERS U
ON A.USER_ID=U.USER_ID;
答案 2 :(得分:0)
SELECT Users.USER_NAME, Users.USER_DOB
FROM Users usr INNER JOIN(
SELECT Transaction.TRANS_STATUS, MAX(Transaction.TRANS_DATE)
FROM Transaction GROUP BY Transaction.TRANS_STATUS) trs ON trs.USER_ID=usr.USER_ID
答案 3 :(得分:0)
您可以使用LAST_VALUE函数
SELECT Top 1
u.User_ID
,u.user_name
,u.user_dob
,u.other_info
,LAST_VALUE(t.Trans_Date) OVER (PARTITION BY t.user_id ORDER BY
t.Trans_Date RANGE BETWEEN UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING) AS Max_Tran_Date
,LAST_VALUE(t.trans_status) OVER (PARTITION BY t.user_id ORDER BY
t.Trans_Date RANGE BETWEEN UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING) as Last_Status
FROM #Users as u
INNER JOIN #Transaction as t ON t.user_id = u.user_id
WHERE u.User_ID = @UserID