简体   繁体   中英

ordering grouped items with group by

The following code used to work for Sql Server.
But I couldnt make it work properly; statuses just wont get in order and display the latest one first.
How can I fix it?

<%
    SQL = "SELECT S.MEMBERID, S.StatusMessage, S.StatusPlace, S.StatusCity, S.StatusDateEntered"
    SQL = SQL & " FROM STATUSES S"
    SQL = SQL & " GROUP BY S.MEMBERID"
    SQL = SQL & " ORDER BY S.StatusDateEntered DESC"
    Set objStatuses = objConn.Execute(SQL)
%>

Your code isn't working because you're doing GROUP on MEMBERID , but you're not aggregating any of the non-grouped columns... which gives you just a random value for every other column for each MEMBERID ... which won't necessarily be the most recent. Next, you're ordering by this scrambled data, which isn't what you're expecting.

To fix this, you need to do a groupwise-max , which can be efficiently implemented as a JOIN to a sub-query containing the MAX(StatusDateEntered) for each MEMBERID :

SELECT 
    S.MEMBERID, 
    S.StatusMessage, 
    S.StatusPlace, 
    S.StatusCity, 
    S.StatusDateEntered
FROM 
    STATUSES S
    JOIN (
        SELECT MEMBERID, MAX(S2.StatusDateEntered) AS MaxStatusDateEntered
        FROM STATUSES
        GROUP BY MEMBERID
    ) S2 
        ON S.StatusDateEntered = S2.MaxStatusDateEntered
        AND S.MEMBERID = S2.MEMBERID
ORDER BY S.StatusDateEntered DESC

Michael thanks a lot for your help. I just found out about the LIMIT clause. It did the trick too.

    SQL = "SELECT S.MEMBERID, S.StatusMessage, S.StatusPlace, S.StatusCity, S.StatusDateEntered"
    SQL = SQL & " FROM STATUSES S"
'   SQL = SQL & " GROUP BY S.MEMBERID"
    SQL = SQL & " ORDER BY S.StatusDateEntered DESC LIMIT 1"
    Set objStatuses = objConn.Execute(SQL)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM