Svaret ligner din tidligere spørgsmål
. Men nu skal det tage højde for, at @user
kunne være begge brugere i meddelelsen.
I dette tilfælde row_number()
er ikke direkte til hjælp.
Her er forskellene. Der er nu en underforespørgsel til at sætte de to brugere i "kanonisk" rækkefølge. Så alle meddelelser mellem dem har den samme User1
og User2
(baseret på alfabetisk rækkefølge).
partition by
klausul bruger disse kolonner, så alle meddelelser er inkluderet i seqnum
beregning. Users
tabel henter nu information om den aktuelle bruger direkte.
select FromUser, ToUser, Message, [Date], UserId, UserFullName, UserName, UserPhoto
from (SELECT CM.FromUser, CM.ToUser, CM.Message, CM.[Date], U.UserId,
U.UserFullName, U.UserName, U.UserPhoto,
row_number() over (partition by CM.User1, CM.User2
order by CM.[Date] desc) as seqnum
FROM (select CM.*,
(case when FromUser < ToUser then FromUser else ToUser end) as User1,
(case when FromUser < ToUser then ToUser else FromUser end) as User2
from ConversationMessages CM
) CM CROSS JOIN
(select *
from Users U
where @user = u.UserName
) U
WHERE @user in (CM.ToUser, CM.FromUser)
) s
WHERE seqnum = 1
ORDER BY s.[Date] DESC ;
EDIT:
Ovenstående returnerer brugeroplysningerne for @user
. For den anden deltager:
select FromUser, ToUser, Message, [Date], UserId, UserFullName, UserName, UserPhoto
from (SELECT CM.FromUser, CM.ToUser, CM.Message, CM.[Date], U.UserId,
U.UserFullName, U.UserName, U.UserPhoto,
row_number() over (partition by CM.User1, CM.User2
order by CM.[Date] desc) as seqnum
FROM (select CM.*,
(case when FromUser < ToUser then FromUser else ToUser end) as User1,
(case when FromUser < ToUser then ToUser else FromUser end) as User2
from ConversationMessages CM
) CM JOIN
Users U
on U.UserName <> @user and
U.UserName in (CM.FromUser, CM.ToUser)
WHERE @user in (CM.ToUser, CM.FromUser)
) s
WHERE seqnum = 1
ORDER BY s.[Date] DESC ;