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

游标嵌套或者递归查询
表是这样的 一张是消费记录 一张是卡信息 还有一张是换卡记录  如果有换卡那么原来的卡记录将不存在,有的是新卡,但旧卡的消费记录是有的  比如客户原先用的是A卡,后来丢了换成B卡, 那么卡信息表里就是B卡,A卡的信息将不存在,换卡记录表里会有记录的(旧卡A,新卡B...),消费记录表里有A卡的消费记录也有B卡

问题:怎么查询顾客的消费信息,将其用过的卡的消费记录汇总到一起(一个顾客可能经过多次换卡,还有的顾客A卡换成B卡,之后又B卡换A卡,换回来了)

用游标的话  效率可能会有点低  如果记录多的话   求方法求帮助....

------解决方案--------------------
更正:

;with cte as (
select a.客户,a.卡号
from 卡信息 a
union all
select a.客户,b.原卡号
from cte a,换卡记录 b
where a.卡号 = b.新卡号
)
select a.客户,b.* from cte a,消费记录 b
where a.卡号= b.卡号

------解决方案--------------------
;with t As(
Select 
a.newCard
,a.oldCard
,b.[客戶]
from [换卡记录] As a
Inner join [卡信息] As b On a.newCard=b.card
Where Not Exists(select 1 from [卡信息] As x
Where x.cards=b.cards
And x.TransferDate>b.TransferDate
)
Union all
Select
a.newCard
,a.oldCard
,t.[客戶]
From [换卡记录] As a
Inner join t On a.newCard=t.oldCard
)
Select
b.*
from t AS a
Inner join [消费记录] As b On a.newCard=b.card Or a.oldCard=b.card