当前位置: 代码迷 >> Sql Server >> 数据库记录查找难题。该如何处理
  详细解决方案

数据库记录查找难题。该如何处理

热度:95   发布时间:2016-04-24 18:53:44.0
数据库记录查找难题。急急急急
在一个表中进行数据查找匹配。表结构如下:
 流水号  客户名称  数量     商业名称
   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.商业名称,
       t1.rownum,
       level + 1 as level
from tt t1
inner join t t2
        on t1.商业名称 = t2.客户名称
)

select 客户名称,数量,商业名称
from tt t1
where level= (select max(level) from tt t2 where t1.rownum = t2.rownum)
/*
客户名称 数量 商业名称
A1 40 B6
A1 50 B7
*/

------解决方案--------------------
try this,

create table cz
(流水号 int,客户名称 varchar(10),数量 int,商业名称 varchar(10))

insert into cz
 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 t as
(select 客户名称,商业名称,数量,流水号,1 'lv' from cz a 
   where not exists(select 1 from cz b where b.客户名称=a.商业名称)
 union all
 select a.客户名称,a.商业名称,a.数量,b.流水号,b.lv+1 'lv'
  from cz a
  inner join t b on a.商业名称=b.客户名称
)
select b.客户名称,b.数量,a.商业名称
 from cz a
 inner join
 (select c.流水号,
         (select d.客户名称 from t d 
          where d.流水号=c.流水号 and d.lv=max(c.lv)) '客户名称',
         (select d.数量 from t d 
          where d.流水号=c.流水号 and d.lv=max(c.lv)-1) '数量'
  from t c
  group by c.流水号) b on a.流水号=b.流水号

/*
客户名称       数量          商业名称
---------- ----------- ----------
A1         40          B6
  相关解决方案