有點明白了;
是不是每個typeid選擇一條離現在最近的?

解决方案 »

  1.   

    第一:你的主键为什么全是1。
    第二:同上所说。你说的取最近的是什么意思。按你说的例子应该是取日期最大的那条记录。
    你将主键不要设成一样的,下面的语句是取日期最大的几项。执行结果为:
    113 2004 6
    1   2004 7
    代码为:select typeid,max(year),max(month) from textdate group by typeid;
    我没有取主键。如果取主键的话。你的主键全是一样的怎么可能。如果加上每条都不一样的主键。那记录全都取出来了。
      

  2.   

    select * from yourtable where 
    ([year]=datepart(year,dateadd(month,1,getdate())) and [month]=datepart(month,dateadd(month,1,getdate()))) 
    or ([year]=datepart(year,getdate()) and [month]=datepart(month,getdate()))
      

  3.   

    --查询
    select * from tb a
    where id=(
    select top 1 id from tb
    where typeid=a.typeid
    order by right(10000+[year],4)+right(100+[month],2) desc)
      

  4.   

    --测试--测试数据
    create table tb(Id int,typeid int,[Year] int,[Month] int)
    insert tb select 1,113,2003,11
    union all select 2,113,2004,5
    union all select 3,113,2004,6
    union all select 4,1  ,2004,7
    union all select 5,1  ,2004,6
    go--查询
    select * from tb a
    where id=(
    select top 1 id from tb
    where typeid=a.typeid
    order by right(10000+[year],4)+right(100+[month],2) desc)
    go--删除测试
    drop table tb/*--测试结果]Id          typeid      Year        Month       
    ----------- ----------- ----------- ----------- 
    3           113         2004        6
    4           1           2004        7(所影响的行数为 2 行)
    --*/
      

  5.   

    select typeid,
     max(([Year]*100+[Month])/100) [Year]
     max(([Year]*100+[Month])%100) [Month]
     from t group by typeid
      

  6.   

    --或者:
    select * from tb a
    where id=(
    select top 1 id from tb
    where typeid=a.typeid
    order by dateadd(year,[year]-1900,dateadd(month,[month],'1900-1-1')) desc)
      

  7.   

    to: zjcxc(邹建) , pbsql(风云)
    我均试了,查出了表中所有数据,没有获得最大日期,表中还有其它字段不止四个,可是其它字段不影响条件
    结果还会有:
    Id          typeid      Year        Month       
    ----------- ----------- ----------- ----------- 
    107         47            2004        6
    109          47           2004        7