2011-11-10 141 views
2

所以我這是在下面的格式構建一個表:選擇的最早和最晚日期

in_click first_name  create_date 
100  joe    2011-10-01 10:01 
100  joe    2011-10-01 10:05 
100  joe    2011-10-01 10:07 
100  joe    2011-10-01 10:08 
100  joe    2011-10-01 10:10 
101  sara   2011-10-01 10:15 
101  sara   2011-10-01 10:17 
101  sara   2011-10-01 10:20 
101  sara   2011-10-01 10:22 

對於每一個名字,我要選擇的第一個和最後一個行。 所以它應該是名字爲joe的第一次約會,以及名字爲joe的最後日期 。有點像if-else語句,但 我只是不確定如何在MySQL中獲取這些信息。

幫助?

我運行下面的查詢,只是得到的一切:

SELECT t.in_click_id, t.keyword, c.lead_id, c.first_name, c.last_name, 
ls.create_date, ls.discriminator, l.affiliate_id 
FROM lead_status AS ls 
INNER JOIN leads AS l ON l.id = ls.lead_id 
INNER JOIN tracker AS t ON l.in_click_id = t.in_click_id 
INNER JOIN contacts AS c ON ls.lead_id = c.lead_id 
WHERE l.affiliate_id NOT IN('1002','1003') 
AND ls.create_date BETWEEN '2011-11-09' AND '2011-11-10'; 

這就是我試圖讓:

in_click first_name  create_date 
100  joe    2011-10-01 10:01 
100  joe    2011-10-01 10:10 
101  sara   2011-10-01 10:15 
101  sara   2011-10-01 10:22 

回答

6

這適用於您提供的數據,不能說它會在MySQL中工作,但它在SQL Server中起作用。

select t.in_click, 
    t.first_name, 
    t.create_date 
from tracker t 
where 
    t.create_date = (select min(create_date) from tracker where in_click = t.in_click) 
    or t.create_date = (select max(create_date) from tracker where in_click = t.in_click) 
0

通過第一個和最後你的意思是在表中的最早日期和最晚日期?如果是這樣,您需要查詢並使用日期的MAX和MIN函數。

+0

是的,這就是我的意思。 – ATMathew