First high-level:
I have a web page that will be showing correspondance between a user and everyone he or she’s been in contact with, but ONLY the last correspondance between them and each other person, resulting in a distinct list of users.
The problem is I’m pulling it all unioned together and grouping them but can’t tell any record apart. I don’t know who sent the message or whether it was an email or instant message.
I thought of creating a dummy column like
'received' AS SentReceived
'sent' AS SentReceived
'email' AS CorrespondanceType
'instant_message' AS CorrespondanceType
but then I lose my disctinction.
for the sake of brevity, i’ll put up some dumbed-down sql outlining where I’m at:
SELECT username, CorrespondanceType, SentReceived, MAX(Date) FROM (
SELECT username, 'email' AS CorrespondanceType, 'received' AS SentReceived, Date FROM tbl_email WHERE user_id='1'
SELECT username, 'email' AS CorrespondanceType, 'sent' AS SentReceived, Date FROM tbl_email WHERE user_id='1'
SELECT username, 'instant_message' AS CorrespondanceType, 'received' AS SentReceived, Date FROM tbl_instant_message WHERE user_id='1'
SELECT username, 'instant_message' AS CorrespondanceType, 'sent' AS SentReceived, Date FROM tbl_instant_message WHERE user_id='1'
) AS tbl_correspondance_summary
GROUP BY username
So if I don’t use the dummy columns, how do I determing the correspondance type and who sent it, and if I do use them, how do I make my results discinct on the username?
this is SQL Server, btw
1 Answer