各位高手您好,我需要在没有任何查询条件的基础上,把我所需要的记录查出来,如下表里有数据如下:
Gather_DTime        Well_Vid  MWell_W_Amount MWell_M_Remain
2003-10-13 11:00:00 010101 246.6797 42754.6601
2003-10-13 12:00:00 010101 246.6797 42754.6601
2003-10-12 12:00:00 010101 246.6797 42754.66012003-10-13 10:00:00 222222 246.6797 42754.6601
2003-10-13 16:00:00 222222 246.6797 42754.6601
2003-10-12 12:00:00 222222 246.6797 42754.66012003-11-13 11:00:00 010101 246.6797 42754.6601
2003-11-13 22:00:00 010101 246.6797 42754.6601
2003-11-12 12:00:00 010101 246.6797 42754.66012003-11-13 10:00:00 222222 246.6797 42754.6601
2003-11-13 12:00:00 222222 246.6797 42754.6601
2003-11-12 12:00:00 222222 246.6797 42754.6601
我想把每个Well_Vid编号不同的记录查询出来,而且这些记录是每个月最后的记录:即
我需要查询出来的是(根据上面的表)
2003-10-13 12:00:00 010101 246.6797 42754.6601
2003-10-13 16:00:00 222222 246.6797 42754.6601
2003-11-13 22:00:00 010101 246.6797 42754.6601
2003-11-13 12:00:00 222222 246.6797 42754.6601
这四条记录我不知道如何选出每个月最晚的记录;帮帮我啊!!!!

解决方案 »

  1.   

    我这里已经调试通过了,给分吧!
    select b.* from (select max(Gather_DTime) as maxDT, Well_Vid from YourTable group by Well_Vid) as a inner join YourTable as b on a.maxDT=b.Gather_DTime and a.Well_Vid=b.Well_Vid
      

  2.   

    好事做到底,刚才没看见月份,其实只要加一点就可以了。
    select b.* from (select max(Gather_DTime) as maxDT, Well_Vid from YourTable group by Well_Vid,MONTH(Gather_DTime)) as a inner join YourTable as b on a.maxDT=b.Gather_DTime and a.Well_Vid=b.Well_Vid
      

  3.   


    上述代码没有考虑到跨年的情况,而且效率也不太理想,你可以试试这个select max(Gather_DTime) as Gather_DTime,Well_Vid,MWell_W_Amount,MWell_M_Remain
    from yourtable
    group by convert(char(7),Gather_DTime,120)
      

  4.   

    yoki(小马哥) :谢谢您,关于跨年的问题我都忽略了;