0
SELECT TOP (100) PERCENT MsgCount.msgcount
    , c.userid
    , c.aspnet_guid
    , c.fname
    , c.lname
    , c.profileimagepath
    , c.profilealbumid
    , p1.msgdate
    , SUBSTRING(p1.msgcontent, 0, 50) AS msgcontent
    , p1.msgtouser
FROM dbo.userprofile AS c 
INNER JOIN dbo.usermessages AS p1 
    ON c.userid = p1.msgfromuser 
LEFT OUTER JOIN dbo.usermessages AS p2 
    ON c.userid = p2.msgfromuser 
    AND (p1.msgdate < p2.msgdate 
          OR p1.msgdate = p2.msgdate 
          AND p1.msgid < p2.msgid) 
LEFT OUTER JOIN  
(
    SELECT msgfromuser
        , COUNT(msgfromuser) AS msgcount
    FROM dbo.usermessages
    GROUP BY msgfromuser
) AS MsgCount 
    ON MsgCount.msgfromuser = p1.msgfromuser
WHERE     (p2.msgid IS NULL)
ORDER BY p2.msgdate DESC
4

2 回答 2

0

我不确定您的表中的数据是什么样的,但是因为您有一个与 p2 的左外连接,所以我假设您期望某个时候没有值并且 p2.msgdate 为空。通过仅按 p2.msgdate (可能为空的列)排序,您将无法获得通过按始终具有值的列进行排序所获得的一致结果。也许按 p1.msgdate 甚至 coalesce(p2.msgdate,p1.msgdate) 排序可能会给您更一致的结果。

SELECT TOP (100) PERCENT MsgCount.msgcount
    , c.userid
    , c.aspnet_guid
    , c.fname
    , c.lname
    , c.profileimagepath
    , c.profilealbumid
    , p1.msgdate
    , SUBSTRING(p1.msgcontent, 0, 50) AS msgcontent
    , p1.msgtouser
FROM dbo.userprofile AS c 
INNER JOIN dbo.usermessages AS p1 
    ON c.userid = p1.msgfromuser 
LEFT OUTER JOIN dbo.usermessages AS p2 
    ON c.userid = p2.msgfromuser 
    AND (p1.msgdate < p2.msgdate 
          OR p1.msgdate = p2.msgdate 
          AND p1.msgid < p2.msgid) 
LEFT OUTER JOIN  
(
    SELECT msgfromuser
        , COUNT(msgfromuser) AS msgcount
    FROM dbo.usermessages
    GROUP BY msgfromuser
) AS MsgCount 
    ON MsgCount.msgfromuser = p1.msgfromuser
WHERE     (p2.msgid IS NULL)
ORDER BY p1.msgdate, p2.msgdate DESC
于 2012-05-11T02:49:31.670 回答
0

也许尝试通过以下方式订购:

p1.msgdate

代替:

p2.msgdate

这只是一个建议:)

于 2012-05-10T23:22:13.450 回答