Fetch Max from a date column grouped by a particular field

寵の児 提交于 2019-12-11 05:09:51

问题


I have a table similar to this:

LogId  RefId   Entered
==================================
1      1       2010-12-01
2      1       2010-12-04
3      2       2010-12-01
4      2       2010-12-06
5      3       2010-12-01
6      1       2010-12-10
7      3       2010-12-05
8      4       2010-12-01

Here, LogId is unique; For each RefId, there are multiple entries with timestamp. What I want to extract is LogId for each latest RefId.

I tried solutions from this link:http://stackoverflow.com/questions/121387/sql-fetch-the-row-which-has-the-max-value-for-a-column. But, it returns multiple rows with same RefId. The LogId as well as RefId should be unique.

Can someone help me with this?

Thanks

Vamyip


回答1:


You need to use a subquery that extracts the latest Entered value for each RefId, and then join your source table to this on RefId, Entered:

SELECT DISTINCT MyTable.LogId, MyTable.Entered FROM MyTable
INNER JOIN (SELECT RefId, MAX(Entered) as Entered FROM MyTable GROUP BY RefId) Latest
ON MyTable.RefId = Latest.RefId AND MyTable.Entered = Latest.Entered



回答2:


Since it appears auto-increment log ID, they would be date/time stamped in sequential order. So, by grabbing the last LogID per Reference ID, you'll have the "most recent" one in the "PreQuery" below, then join based on that single ID to the original table to get the actual date stamp info (or other details) you need from the actual log.

select PreQuery.RefID,
       PreQuery.LastLogEntry,
       L.Entered
   from 
      ( select RefID,
               Max( LogID ) LastLogEntry
           from 
               YourLog
           group by
               RefID ) PreQuery,
      YourLog L
   where
      PreQuery.LastLogEntry = L.LogID



回答3:


To handle the duplicates correctly:

SELECT  m.*
FROM    (
        SELECT  DISTINCT refid
        FROM    mytable
        ) md
JOIN    mytable m
ON      m.LogID = 
        (
        SELECT  LogID
        FROM    mytable mi
        WHERE   mi.refid = md.refid
        ORDER BY
                mi.refid DESC, mi.entered DESC, mi.logid DESC
        LIMIT 1
        )

Create an index on mytable (refid, entered, logid) for this to work fast.



来源:https://stackoverflow.com/questions/4713878/fetch-max-from-a-date-column-grouped-by-a-particular-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!