日期:2014-05-18  浏览次数:20490 次

根据时间查询,时间最大的所有数据。
比如A表:

name date
A 2012.01
A 2012.02
A 2012.03

B 2012.02
B 2012.03
B 2012.04

C 2012.03
C 2012.04
C 2012.05

最终得到数据为:
A 2012.03
B 2012.04
C 2012.05

得到每个人时间最大的数据。
Sql语句该如何写呢?谢谢。

------解决方案--------------------

SQL code
select a.name,date a.from(
select row_number()over(partition by name order by cast(right(date,2) as int) desc) as num,*from tbl)a
where num=1

------解决方案--------------------
SQL code

CREATE TABLE #t(NAME CHAR(2),dates DATE)
insert into #t
select 'A', '201201' union all
select 'A', '201202' union all
select 'A', '201203' union all

select 'B', '201202' union all
select 'B', '201203' union all
select 'B', '201204' union all

select 'C', '201203' union all
select 'C', '201204' union all
select 'C', '201205'
SELECT NAME,MAX(dates) FROM #t
GROUP BY NAME

------解决方案--------------------
SQL code
select * from A t
where not exists(select 1 from name=t.name and [date]>t.[date])

------解决方案--------------------
探讨

SQL code
select * from A t
where not exists(select 1 from name=t.name and [date]>t.[date])