日期:2014-05-17  浏览次数:20435 次

求句SQL,在线等。。。感谢..
表A,
Name       Year      month
A        2011       3
B        2011       7  
B        2011       5
C        2011       9
C        2013       8
C        2013       5
C        2011       3

我想得到(日期最大的),年和月,是2个字段.
最后结果如:
Name       Year      month
A        2011        3
B        2011        7 
C        2013        8

感谢,在线等///

------解决方案--------------------
select name,max(Year)Year,min(month)month from
(
select Name ,max(Year)Year,max(month)month
from a group by Name ,Year      
)x group by name

结果是出来啦,感觉不太好
------解决方案--------------------
if object_id('t') is not null drop table t
create table t
(
name varchar(10),
year int,
month int
)

insert into t
select 'A',2011,3 union
select 'B',2011,7 union
select 'B',2011,5 union
select 'C',2011,9 union
select 'C',2013,8 union
select 'C',2013,5 union
select 'C',2013,3
go

with cte as
(
select t.name,max(cast(str(t.year,4)+'/'+right('0'+str(t.month,2),2)+'/01' as datetime)) date
from
t
group by t.name
)
select cte.name,DATENAME(YEAR,cte.date) year,DATENAME(MONTH,cte.date) month
from cte