我找不到通过加入同一个表并在新行上显示结果来获取同一个id的timestamp列的最小值和最大值的方法
例如
No | Name | Date
1 John 01/01/2010
4 Chris 01/02/2009
1 John 01/01/2011
6 Alex 02/02/2010
1 Alex 01/01/2012
4 Norman 01/03/2012
6 Joshua 03/02/2012
I should somehow get :
No | Name | Date
1 John 01/01/2010
1 Alex 01/01/2012
4 Chris 01/02/2009
4 Norman 01/03/2012
6 Alex 01/01/2012
6 Joshua 03/02/2012
答案 0 :(得分:0)
简单的MIN
和MAX
会完成这项工作还是会有更复杂的要求?
SELECT no, name, MIN(date) as MinDate, MAX(date) as MaxDate
FROM temp t
GROUP BY no, name
ORDER BY no
演示:http://sqlfiddle.com/#!3/8243c/3
编辑:可以这样做:
select t.no, name, mindate, maxdate
from temp t
left join (select min(date) as mindate, no
from temp
group by no) t2 on t.no = t2.no
left join (select max(date) as maxdate, no
from temp
group by no) t3 on t.no = t3.no
答案 1 :(得分:0)
这将为您提供所需的确切输出:
select no, name, date
from temp t
where date = (select min(x.date) from temp x where x.no = t.no)
or date = (select max(x.date) from temp x where x.no = t.no)
order by no, date
SQL小提琴演示:http://sqlfiddle.com/#!3/8243c/6/0
编辑 - 如果您想使用JOIN:
select t.no, t.name, t.date
from temp t
join (select no, min(date) as min_date, max(date) as max_date
from temp
group by no) x
on (t.no = x.no and t.date = min_date)
or (t.no = x.no and t.date = max_date)
order by t.no, t.date
http://sqlfiddle.com/#!3/8243c/19/0
(相同的输出)