金额               货物名  客户名         日期3.000000          0111 b 2011-01-01 00:00:00.000
100.000000 0111 A 2011-01-01 00:00:00.000
101.000000 0111 b 2011-01-02 00:00:00.000
102.000000 0111 A 2011-01-03 00:00:00.000怎样用SQL求出 同一个货物每个客户最新日期的金额.

解决方案 »

  1.   

    select * from tb a where not exists(select 1 from tb where 客户a.客户 and 货物名=a.货物名 and 日期>a.日期)
      

  2.   

    select * from tb a where not exists(select 1 from tb where 客户=a.客户 and 货物名=a.货物名 and 日期>a.日期)
      

  3.   

    select * from tb t where 日期=(select max(日期) from tb where 客户=t.客户 and 货物名=t.货物名 )
      

  4.   


    select * 
    from table a
    inner join
    (select 货物名,客户名,max(日期) 日期
    from table
    group by 货物名,客户名) b
    on a.货物名=b.货物名 and a.客户名=b.客户名 and a.日期=b.日期
      

  5.   


    select t.* from tb t where 日期 = (select max(日期) from tb where 货物名 = t.货物名 and 客户名 = t.客户名)
    select t.* from tb t where not exists (select m1 from tb where 货物名 = t.货物名 and 客户名 = t.客户名 and 日期 > t.日期)
      

  6.   

    select * from tb a where not exists(select 1 from tb where 客户=a.客户 
    and 货物名=a.货物名 and 日期>a.日期)
      

  7.   

    create table tb(金额 decimal(18,6),货物名 varchar(10),客户名 varchar(10),日期 datetime)
    insert into tb values(3.000000   ,'0111', 'b', '2011-01-01 00:00:00.000')
    insert into tb values(100.000000 ,'0111', 'A', '2011-01-01 00:00:00.000')
    insert into tb values(101.000000 ,'0111', 'b', '2011-01-02 00:00:00.000')
    insert into tb values(102.000000 ,'0111', 'A', '2011-01-03 00:00:00.000')
    goselect t.* from tb t where 日期 = (select max(日期) from tb where 货物名 = t.货物名 and 客户名 = t.客户名) order by t.货物名,t.客户名
    /*
    金额                   货物名        客户名        日期                                                     
    -------------------- ---------- ---------- ------------------------------------------------------ 
    102.000000           0111       A          2011-01-03 00:00:00.000
    101.000000           0111       b          2011-01-02 00:00:00.000(所影响的行数为 2 行)
    */
    select t.* from tb t where not exists (select 1 from tb where 货物名 = t.货物名 and 客户名 = t.客户名 and 日期 > t.日期) order by t.货物名,t.客户名
    /*
    金额                   货物名        客户名        日期                                                     
    -------------------- ---------- ---------- ------------------------------------------------------ 
    102.000000           0111       A          2011-01-03 00:00:00.000
    101.000000           0111       b          2011-01-02 00:00:00.000(所影响的行数为 2 行)*/
    drop table tb
      

  8.   

    select * from tb t where 日期=(select max(日期) from tb where 客户=t.客户 and 货物名=t.货物名 )