【在线速结贴】SQL 怎样根据两个表最近值来匹配实现汇总?(见正文,有数据)
1、有一个物料所需表A:
A1(物料) A2(规格1) A3(规格2) A4(数量)
----------------------------------------------------
s001 825 890 1
s002 799 1050 2
s003 1010 950 2
s004 859 900 2
s005 859 1060 3
2、标准库存表B
B1 B2 B3
-----------------------
t001 900 900
t002 1000 1100
t003 900 1000
3、现在想汇总成标准B的规格,表A规格不满整数的取其离规格最近的,两个规格参数B2和B3都不能比A2和A3小,但是A2和A3或者B2和B3可以颠倒过来比对是可以的,比如:
s001(825*890) --> 取t001(900*900)
s002(799*050) --> 取t002(1000*1100)
s003(1010*950) --> 取t002(1000*1100)
s004(859*900) --> 取t001(900*900)
s005(859*1060) --> 取t003(900*1000)
4、最后的汇总效果如下:
规格 合计
---------------
t001 3 注释分别是s001(A4 x 1)+s004(A4 x 2)=3
t002 2 同上
t003 1
请问一下大家怎样来实现上述这种汇总?不知道大家看明白了没有。如有不明白处我再次补充说明一下。
create table a (a1 varchar(100),a2 int,a3 int,a4 int)
insert into a
SELECT 's001',825 ,890 ,1 UNION ALL
SELECT 's002',799 ,1050,2 UNION ALL
SELECT 's003',1010,950 ,2 UNION ALL
SELECT 's004',859 ,900 ,2 UNION ALL
SELECT 's005',859 ,1060,3
create table b (B1 varchar(100),B2 int,B3 int)
insert into b
SELECT 't001',900 ,900 UNION ALL
SELECT 't002',1000,1100 UNION ALL
SELECT 't003',900 ,1000
;with tt
as
(
select a.*,
b.*,
row_number() over(partition by a.a1
order by abs(a.a2-b.b2) + abs(a.a3 - b.b3)) as rownum
from a
inner join b
on (b.b2 >= a.a2 and b.b3 >= a.a3) or
(b.b3 >= a.a2 and b.b2 >= a.a3)
)
select b1,
sum(a4) as 合计
from tt
where rownum = 1
group by b1
/*
b1 合计
t0013
t0027
*/