Very much stuck with a certain query I'm trying to run.
Here's the table structure -
+--------+----------+--------+
| caseID | status | update |
+--------+----------+--------+
1 New 3-4-2013
1 Open 3-5-2013
2 New 3-5-2013
3 Closed 3-5-2013
I want my query return the most recent row and then only display rows where status = 'New', ie in the sample data only the row caseID = 2 should be returned.
I have this query
SELECT * FROM (SELECT * FROM table ORDER BY update DESC) AS foo GROUP BY caseID
That query returns the most recent row for each caseID. Now I'm struck with the part of just displaying where status = 'New'.
I tried this and got an #1064 SQL error
`SELECT * FROM (SELECT * FROM table ORDER BY update DESC) AS foo GROUP BY caseID WHERE status = 'New'
I tried this and it returns all rows where status='New' even if they are not the most recent. Which is not what I want.
SELECT * FROM (SELECT * FROM table ORDER BY update DESC) AS foo WHERE status = 'New' GROUP BY caseID
I appreciate the help in advance.
Something like this should work.
select * from data
join (select caseId, max(`update`) as
`update` from data
where status = 'New'
group by caseId) as filter
on filter.caseId = data.caseId and filter.`update` = data.`update`
where data.status = 'New'
group by data.caseId;
Basically, you're joining the table to itself, but the inner join is identifying the most recent record that you're trying to retrieve.
Find the date of the most recent row using group by
, then join
and filter:
select s.*
from structure s join
(select caseId, max(update) as maxupdate
from structure s
group by caseid
) ss
on s.caseId = ss.caseId and s.update = ss.maxupdate
where s.status = 'New';
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.