金额 货物名 客户名 日期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求出 同一个货物每个客户最新日期的金额.
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求出 同一个货物每个客户最新日期的金额.
select *
from table a
inner join
(select 货物名,客户名,max(日期) 日期
from table
group by 货物名,客户名) b
on a.货物名=b.货物名 and a.客户名=b.客户名 and a.日期=b.日期
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.日期)
and 货物名=a.货物名 and 日期>a.日期)
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