可能重复:
MAX Date for each worker
我正在编写一个sql语句来获取已为每个用户提交和批准的最新会话。
以下是一些关于我的数据库的信息,应该解释这种情况:
User_Profile
表,密钥为GUID
,Tmn_Session
密钥为SESSION_ID
的密钥表和密钥为Auth_Table
的密钥表
AUTH_SESSION_ID
。Tmn_Sessions
),他们选择了一些提交。他们能
有许多提交,其中一些已获批准但是
只有我们关心的批准会议才是最近的会议。Auth_Table
。表格是授权的
Auth_Table.FINANCE_RESPONSE='Yes'
和授权时间
发生在Auth_Table.FINANCE_TIMESTAMP
。Tmn_Session
提及Auth_Table.AUTH_SESSION_ID
一次
我在每个Auth_Table
找到了最近批准的行
User_Profiles
中的用户我可以从中获取关联的SESSION_ID
Tmn_Session
。这就是目标。我以为我知道怎么做但我多年没碰过SQL了。这是我试图为每个用户找到最大的时间戳。这显然是错的。它返回一个数字而不是一组最大时间戳,每个用户一个。
SELECT MAX(Auth_Table.FINANCE_TIMESTAMP) FROM Auth_Table, User_Profiles WHERE Auth_Table.AUTH_USER=User_Profiles.GUID AND Auth_Table.FINANCE_RESPONSE='Yes'
所以有关如何达到每个用户最近一次会话SESSION_ID
的最终目标的任何建议。或者对第一步修复我的尝试的建议表示赞赏。
提前致谢。
更新:我解决了。它与链接的解决方案有点不同。以下是我试图描述的表格。
CREATE TABLE current_sessions
SELECT users.GUID, users.FIN_ACC_NUM, SESSION_ID, CURRENT_SESSION_TIMESTAMP
FROM User_Profiles AS users
LEFT JOIN
(
(
SELECT auth.AUTH_SESSION_ID, auth.AUTH_USER, auth.FINANCE_TIMESTAMP AS CURRENT_SESSION_TIMESTAMP
FROM Auth_Table AS auth
INNER JOIN
(
SELECT AUTH_USER, MAX(FINANCE_TIMESTAMP) AS MAX_TIMESTAMP
FROM Auth_Table
WHERE FINANCE_RESPONSE='Yes'
GROUP BY AUTH_USER
) AS max_dates
ON auth.AUTH_USER = max_dates.AUTH_USER AND auth.FINANCE_TIMESTAMP = max_dates.MAX_TIMESTAMP
) AS latest_sessions
LEFT JOIN
(
SELECT SESSION_ID, AUTH_SESSION_ID, GUID, HOME_ASSIGNMENT_SESSION_ID, INTERNATIONAL_ASSIGNMENT_SESSION_ID, OS_ASSIGNMENT_START_DATE, OS_ASSIGNMENT_END_DATE
FROM Tmn_Sessions
WHERE (HOME_ASSIGNMENT_SESSION_ID IS NULL AND INTERNATIONAL_ASSIGNMENT_SESSION_ID IS NULL)
OR (HOME_ASSIGNMENT_SESSION_ID IS NOT NULL AND INTERNATIONAL_ASSIGNMENT_SESSION_ID IS NULL AND STR_TO_DATE(OS_ASSIGNMENT_START_DATE, '%d-%m-%Y') < CURRENT_DATE() AND STR_TO_DATE(OS_ASSIGNMENT_END_DATE, '%d-%m-%Y') > CURRENT_DATE())
OR (HOME_ASSIGNMENT_SESSION_ID IS NULL AND INTERNATIONAL_ASSIGNMENT_SESSION_ID IS NOT NULL AND STR_TO_DATE(OS_ASSIGNMENT_START_DATE, '%d-%m-%Y') < CURRENT_DATE())
) AS active_sessions
ON latest_sessions.AUTH_SESSION_ID = active_sessions.AUTH_SESSION_ID
)
ON users.GUID = AUTH_USER;
INSERT INTO Low_Account (FIN_ACC_NUM, CURRENT_SESSION_ID, TMN_EFFECTIVE_DATE)
SELECT DISTINCT users.FIN_ACC_NUM, most_recent_session_for_fan.SESSION_ID, most_recent_session_for_fan.CURRENT_SESSION_TIMESTAMP
FROM User_Profiles AS users
LEFT JOIN
(
SELECT cs.*
FROM current_sessions AS cs
INNER JOIN
(
SELECT FIN_ACC_NUM, MAX(CURRENT_SESSION_TIMESTAMP) AS MAX_DATE
FROM current_sessions
GROUP BY FIN_ACC_NUM
) AS filtered_cs
ON cs.FIN_ACC_NUM = filtered_cs.FIN_ACC_NUM AND cs.CURRENT_SESSION_TIMESTAMP = filtered_cs.MAX_DATE
) as most_recent_session_for_fan
ON users.FIN_ACC_NUM = most_recent_session_for_fan.FIN_ACC_NUM;
DROP TABLE current_sessions;