开发者

mySQL query with date range and selecting only the most recent records for each ID

开发者 https://www.devze.com 2023-04-11 23:25 出处:网络
I have the following table: RecordIDStatusDateTimestamp ----------------------------------------------------------

I have the following table:

Record   ID   Status     Date          Timestamp
----------------------------------------------------------
1        1    waiting    2010-02-02    2010-02-02 12:00:00
2        1    finished   2010-02-02    2010-02-02 12:30:00
3        2    waiting    2009-02-02    2009-02-02 12:00:00

I want to get the records where Date is between 2010-01-01 and 2010-03-03. (this should give me Records 1 and 2)

Further I want to get only the latest (having most recent timestamp) for each ID. (this should give me Record 2 only).

I am not sure how I need to structure my query. I have managed to build the following query:

SELECT   `Record` `ID`, MAX(  `Timestamp` ) 
FROM     `myTable` 
WHERE    `Date` 
BETWEEN  '2010-01-01'
AND      '2011-03-03'
GROUP BY `ID` 

The problem with the above query is that for some reason it is giving me the following result:

Record   ID   Timestamp
---------------------------------
1        1    2010-02-02 12:30:00

which is correct except that the Record field should h开发者_C百科ave the value 2 and not 1.


SELECT t1.* 
FROM `myTable` t1
INNER JOIN
(
SELECT MAX(`Timestamp`) as Timestamp
FROM     `myTable`
WHERE    `Date` 
BETWEEN  '2010-01-01'
AND      '2011-03-03'
GROUP BY `ID` 
) t2
ON t1.Timestamp = t2.Timestamp


Try the below query

SELECT   `Record` `ID`,Timestamp
FROM     `myTable` 
WHERE    `Date` 
BETWEEN  '2010-01-01'
AND      '2011-03-03'
Order by `Timestamp` desc
limit 1
0

精彩评论

暂无评论...
验证码 换一张
取 消