2012-10-02 43 views
1

我有一個表像這樣 -MySQL查詢來獲得最後的狀態值進入

+----+---------------------+------------+---------+--------------------+ 
| id | check_date   | number  | status | sid    | 
+----+---------------------+------------+---------+--------------------+ 
| 5 | 2012-09-29 17:44:34 | 3366064235 | SUCCESS | 1348940709163284 | 
| 6 | 2012-09-29 19:40:30 | 3366064235 | FAILED | 12345678876543  | 
| 7 | 2012-09-29 17:47:30 | 4466064235 | SUCCESS | 7895345678876543 | 
| 8 | 2012-09-29 19:47:30 | 4466064235 | SUCCESS | 789876545678876543 | 
+----+---------------------+------------+---------+--------------------+ 

我想每個號碼的最後更新的狀態。我如何得到這個?我通過check_date desc嘗試按編號順序進行分組,但它不起作用。

回答

5

您可以使用這樣的事情:

select t1.id, 
    t1.check_date, 
    t1.number, 
    t1.status 
from yourtable t1 
inner join 
(
    select max(check_date) maxdate, number 
    from yourtable 
    group by number 
) t2 
    on t1.check_date = t2.maxdate 
    and t1.number = t2.number 

SQL Fiddle with demo

+0

我們不能做到這一點,而不使用子查詢? – Shwetanka

+0

@Shwetanka它取決於你想要返回什麼,如果你只想要日期和數字,那麼是的,但是你想知道狀態,這個組將通過它們來區分它們。看到這個演示 - http://sqlfiddle.com/#!2/cb084/7。無論哪種方式,您都需要通過'JOIN'或'WHERE'子句中的某種子查詢 – Taryn

0
select number, Status, Check_date from MYTable A 
where check_date = (select max(Check_date) from MYTable where number=A.number)