[英]MySQL: Select last from group, but with conditions
我有下表:
name created_for created_on status
jen 2012-05-27 2012-02-15 12:14:09 Y
joe 2012-10-01 2012-02-15 12:22:09 Y
bob 2012-10-01 2012-02-15 12:47:09 N
jim 2012-10-01 2012-02-24 12:47:09 N
jim 2012-10-01 2012-02-29 12:47:09 Y
sam 2012-10-01 2012-03-11 12:47:09 N
sam 2012-10-01 2012-03-15 12:47:09 C
sam 2012-10-01 2012-03-22 12:47:09 Y
tom 2012-10-01 2012-04-10 12:47:09 N
tom 2012-10-01 2012-04-11 12:47:09 N
我要返回的是名稱的最后一行,即created_for日期為2012-10-01的每個人的created_on,但僅當最后一個條目的狀態為N時,所以我要返回上表回來:
name created_on
bob 2012-02-15 12:47:09
tom 2012-04-11 12:47:09
身份狀況就是讓我大跌眼鏡的原因。 我似乎無法弄清楚在何處放置“ where status ='N'”以獲得正確的結果。
嘗試這個:
SELECT t1.*
FROM
(
SELECT name, MAX(created_on) MaxDate
FROM YourTableName
GROUP BY name
) t1 INNER JOIN YourTableName t2 on t1.name = t2.name
AND t1.MaxDate = t2.created_on
WHERE t2.created_for = '2012-10-01'
AND t2.status = 'N'
select t.*
from MyTable t
inner join (
select name, max(created_on) max_created_on
from MyTable
where created_for = '2012-10-01'
group by name
) tm on t.name = tm.name and t.created_on = tm.max_created_on
where t.status = 'N'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.