Hi @Smile_28
First, SQLServer doesn't have TO_DATE function. You have to use convert in SQL Sever. Please refer to this link for more details.
Second,
the reason why you found two records for the clientname TEST_A_1 is because there is group by sessions.version
in your groupby statement, so when a clientname has several different versions, there will be several different records.
Third, there are several ways to deal with this issue:
You can use Cross Apply like this:
SELECT DISTINCT C.USERNAME,C.CLIENTNAME AS "CLIENT NAME",C.VERSION,U.TASK,C.LOGINTIME AS "LOGIN TIME"
FROM users U RIGHT JOIN sessions S on U.USERNAME = S.USERNAME
CROSS APPLY(SELECT TOP(1) USERNAME,CLIENTNAME,VERSION,LOGINTIME FROM sessions WHERE USERNAME=S.USERNAME AND CLIENTNAME=S.CLIENTNAME ORDER BY LOGINTIME DESC )C
WHERE S.USERNAME = 'TEST_PROD' AND S.LOGINTIME >='15-FEB-22'
Or you can have a try on ROW_NUMBER function, like this:
;WITH CTE AS
(SELECT *,ROW_NUMBER()OVER(PARTITION BY UserName,ClientName ORDER BY LOGIN_TIME DESC)AS RNum
FROM #sessions
)SELECT DISTINCT C.USERNAME,C.CLIENTNAME AS "CLIENT NAME",C.VERSION,U.TASK,C.LOGIN_TIME AS "LOGIN TIME"
FROM #users U RIGHT JOIN CTE C ON U.USERNAME = C.USERNAME
WHERE C.USERNAME = 'TEST_PROD' AND C.LOGIN_TIME >='15-FEB-22' AND C.RNum=1
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.