table   name:   tb_main 
fd_id       fd_operate_type         fd_reason     doc_create_time                     fd_main_id     doc_creator_id     
    1                   01                       NULL             2007-11-05   06:27:17.263         7                     2065 
    2                   04                       NULL             2007-11-05   06:25:58.897         7                     2065 
    3                   01                       NULL             2007-11-05   06:53:11.500         7                     2065 
    4                   02                       asd              2007-11-05   06:53:50.507         7                     2065 
    5                   04                       NULL             2007-11-05   06:54:33.157         7                     2065 如果有如上所示的数据, 
我需要的结果是,得到fd_operate_type为01或者02且fd_main_id为7的数据,在得到数据中,取doc_creator_id相同的且doc_create_time最大的一个,返回的结果必须是整个表的集合。也就是HIbernate中必须要得到该表的一个对象。请问大家这个SQL语句该怎么写?或者HQL语句?谢谢。

解决方案 »

  1.   

    with T as 
    (select * from tb_main where fd_main_id=7 and fd_operate_type in ('01','02'))
    select * from T
    where doc_create_time=(select max(doc_create_time) from T t1 where doc_creator_id=T.doc_creator_id)
      

  2.   

    1楼的代码只能在SQL2005下执行,如果是SQL2000,用下面的:select * from (select * from tb_main where fd_main_id=7 and fd_operate_type in ('01','02')) T
    where doc_create_time=
    (select max(doc_create_time) from 
    (select * from tb_main where fd_main_id=7 and fd_operate_type in ('01','02')) t1 
    where doc_creator_id=T.doc_creator_id)
      

  3.   

    这样的SQL语句可是可以查询到结果,但是写HQL就不行了,Hibernate不支持在from关键字后面直接实用子查询,只允许在where后面写,
    否则就会报错,说语法错误,unexpected token: (