求有关在重复记录中取日期最晚记录的SQL脚本
由于数据非常庞大,需要求效率尽可能高,
Table1字段及数据如下:
BookID,BookName, P_Date,     P_Time,   P_Address,  P_User
1001   书名1    2007-07-02   10:08:52  北京1路    张三
1001   书名1    2007-07-03   09:20:10  北京2路    张三
1001   书名1    2007-07-02   17:20:50  北京3路    李四
1002   书名2    2007-06-05   14:20:10  北京4路    李四
1002   书名2    2007-04-30   19:50:25  北京5路    李四
....目标查询结果:
1001   书名1    2007-07-03   09:20:10  北京2路    张三
1002   书名2    2007-06-05   14:20:10  北京4路    李四我目前的方法是:
select substring(...) MaxDate,substring.... from(select BookID,BookName,max(P_Date+P_Time+P_Address+P_User) as sTempfrom Table1 group by BookID,BookName) TempTable现在的问题:1、上面用substring取出日期、时间都没问题,因为着两个字段的长度是固定的;但地址和用户就感觉有点棘手,中间不知加什么符号来分割比较好,因为担心用户的地址甚至用户名里有这些符号,这样就可能导致分割出来的数据错位了2、这种写法总觉得效率上不是很高,有没有更优化速度的写法?

解决方案 »

  1.   

    select * from table as a where not exists
    (select 1 from table where BookID = a.BookID and P_Date + P_Time > a.P_Date + a.P_Time)
      

  2.   

    select * from table1 a
    where not exists (
    select 1 from table1
    where BookID=a.BookID
    and cast(P_Date+' '+P_Time as datetime)>cast(a.P_Date+' '+a.P_Time as datetime)
    )
      

  3.   

    trySelect * From Table1 A 
    Where Not Exists
    (Select BookID From Table1 Where BookID = A.BookID And BookName = A.BookName And ((P_Date > A.P_Date) Or (P_Date = A.P_Date And P_Time > A.P_Time)))
      

  4.   

    可能这样效率高些select * from table1 a
    where not exists (
    select 1 from table1
    where BookID=a.BookID
    and (P_Date>a.P_Date 
    or P_Date=a.P_Date and P_Time>a.P_Time)
    )
      

  5.   

    ----方法1:
    select * from table as a where not exists
    (select 1 from table where BookID = a.BookID and P_Date + P_Time > a.P_Date + a.P_Time)----方法2:
    select a.* from table as a
    inner join 
    (select BookID,max(P_Date + P_Time) as dt from table group by BookID) as b 
    on a.BookID = b.BookID and a.P_Date + a.P_Time = b.dt