2013-10-23 48 views
1

我試圖將一個表加入到它自己的一個子集中,並且遇到了麻煩。我輸入包含ID和日期如下:加入到同一個表的子集中

2013-10-14 eca02319d91421445f82d570960c5d0c 

2013-10-15 eca02319d91421445f82d570960c5d0c 

2013-10-16 eca02319d91421445f82d570960c5d0c 

2013-10-17 eca02319d91421445f82d570960c5d0c 

2013-10-19 eca02319d91421445f82d570960c5d0c 

2013-10-21 eca02319d91421445f82d570960c5d0c 

我的目標是確定看到了對於每一日期同一ID中的最後較早日期,如:

 Date   ID         Last Date 
    2013-10-21 eca02319d91421445f82d570960c5d0c  2013-10-19 

    2013-10-19 eca02319d91421445f82d570960c5d0c  2013-10-17 
    etc. 

使用下面的SQL ,我得到下面的輸出:

select a.Day,a.entity, b.Day from Visitor a 
    LEFT OUTER JOIN Visitor b 
on a.entity = b.entity 
     and b.day < a.day 
where b.day is not null 

output 

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-14 

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-15 

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-17 

2013-10-21 eca02319d91421445f82d570960c5d0c 2013-10-19 

2013-10-19 eca02319d91421445f82d570960c5d0c 2013-10-14 

2013-10-19 eca02319d91421445f82d570960c5d0c 2013-10-15 

什麼是需要得到降序排列爲a.day的每個實例只有一個記錄,以及過程b.day?

預先感謝您!

回答

1

嘗試這樣:

SELECT distinct a.date, a.id, (select d.date from data d 
     where a.date > d.date AND a.id = d.id 
     order by d.date desc limit 1) as last_date 
FROM data a where (select d.date from data d 
     where a.date > d.date AND a.id = d.id 
     order by d.date desc limit 1) is not null 
ORDER by a.date desc; 

SQL Fiddle

+0

這確實正是我需要的。非常感謝你! –

+0

@DaveMcLelland如果它適合你,請將答案標記爲正確。謝謝。 – 7alhashmi