日期:2014-05-17  浏览次数:20472 次

数据库记录查找难题。急急急急
在一个表中进行数据查找匹配。表结构如下:
 流水号  客户名称  数量     商业名称
   1      A1     100       B1
   2      B1      50       B3
   3      B1      40       B2
   4      B3      60       B5
   5      B2     100       B6
   6      B5     100       B7

最终要得到
A1     50    B7
A1     40    B6  
数据库,记录,匹配

------解决方案--------------------
规则是什么?看不懂
------解决方案--------------------
怎么弄出来的啊?
------解决方案--------------------
应该是嵌套递归查找,找出客户的商业名称,又以商业名称为客户再找它下级一商业名称
------解决方案--------------------
create table t
(
流水号 int, 客户名称  varchar(10),数量 int, 商业名称 varchar(10)
)
 

insert into t 
select   1,      'A1' ,    100,      'B1'
union all select   2,      'B1' ,    50 ,      'B3'
union all select   3,      'B1' ,    40 ,      'B2'
union all select   4,      'B3' ,    60 ,      'B5'
union all select   5,      'B2' ,    100,      'B6'
union all select   6,      'B5' ,    100,      'B7'


;with tt
as
(
select t.客户名称,
       isnull(tt.数量,t.数量) 数量,
       tt.商业名称,
       row_number() over(order by getdate()) as rownum,
       1 as level
from t
left join t tt
       on tt.客户名称 = t.商业名称
where  t.客户名称 = 'A1'

union all

select t1.客户名称,
       t1.数量,       
       t2.商业名称,