SQL query to combine two user tables, remove duplcates and find the latest update entry for each user

StackOverflow https://stackoverflow.com/questions/22310719

문제

I have two SQL tables. TableA has a list of active users, TableB has a list of all help tickets the users submitted with emails and submit dates.

I need to output a list of users that exist in Table A & Table B (excluding users only in TableB) along with the date of the last help ticket they submitted. This is because several users were removed from the active users table, but their help tickets remain in the second table.

Table Fields:

eUser
eUserName, eEmailAddress

Work_Orders
txtContactEmail, SubmitDate


Desired output:
eUserName, eEmailAddress, SubmitDate

My Attempt

SELECT   eUser.eUserName
       , eUser.eEMailAddress
       , Work_Orders.txtContactEmail
       , max(Work_Orders.dtRequest) lastupdate 
FROM eUser inner join Work_Orders 
on eUser.eEMailAddress = Work_Orders.txtContactEmail 
group by eUser.eUserName
       , eUser.eEMailAddress
       , Work_Orders.txtContactEmail
도움이 되었습니까?

해결책

SELECT  A.eUserName,
        A.eEmailAddress,
        B.MaxSubmitDate
FROM TableA AS A
INNER JOIN (SELECT txtContactEmail, MAX(SubmitDate) MaxSubmitDate
            FROM TableB
            GROUP BY txtContactEmail) AS B
    ON A.eEmailAddress = B.txtContactEmail
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top