日期:2014-05-18  浏览次数:20718 次

如何过滤出每一个商品的在不同购进单位单据编号最大的那条记录?
如何过滤出每一个商品的每一个购进单位的,单据编号最大的那条记录?
(一个商品可能在多个单位购进,自取最近的一条)

表结构如下
(举少量数据为例)

spbh dwbh rq
spid1 A 2012-04-01
spid1 A 2012-03-01
spid1 B 2012-03-01
spid2 A 2012-04-01
spid2 B 2012-03-01
spid2 B 2012-02-01
spid3 A 2012-03-01
spid3 A 2012-02-01
......
---------------------------------------

想得到这样的结果

spbh dwbh rq
spid1 A 2012-04-01
spid1 B 2012-03-01
spid2 A 2012-04-01
spid2 B 2012-03-01
spid3 A 2012-03-01





------解决方案--------------------
SQL code

select spbh ,dwbh, max(rq)rq from tb group by spbh,dwbh

------解决方案--------------------
SQL code


--> 测试数据:[tbl]
if object_id('[tbl]') is not null drop table [tbl]
create table [tbl]([spbh] varchar(5),[dwbh] varchar(1),[rq] datetime)
insert [tbl]
select 'spid1','A','2012-04-01' union all
select 'spid1','A','2012-03-01' union all
select 'spid1','B','2012-03-01' union all
select 'spid2','A','2012-04-01' union all
select 'spid2','B','2012-03-01' union all
select 'spid2','B','2012-02-01' union all
select 'spid3','A','2012-03-01' union all
select 'spid3','A','2012-02-01'

--2005以上
select [spbh],[dwbh],[rq] from(
select row=ROW_NUMBER()over(partition by [spbh],[dwbh] order by [rq] desc),
    * from tbl)a
where row=1
--2000
--1
select * from tbl a
    where [rq]=(select MAX([rq]) from tbl b where a.spbh=b.spbh and a.dwbh=b.dwbh)
    order by [spbh],[dwbh]
--2
select spbh ,dwbh, max(rq)rq from tbl group by spbh,dwbh

--情况简单选择2就好了,复杂了使用1或者2005以上版本使用row_number
/*
spbh    dwbh    rq
spid1    A    2012-04-01 00:00:00.000
spid1    B    2012-03-01 00:00:00.000
spid2    A    2012-04-01 00:00:00.000
spid2    B    2012-03-01 00:00:00.000
spid3    A    2012-03-01 00:00:00.000
*/