表是这样的 一张是消费记录 一张是卡信息 还有一张是换卡记录  如果有换卡那么原来的卡记录将不存在,有的是新卡,但旧卡的消费记录是有的  比如客户原先用的是A卡,后来丢了换成B卡, 那么卡信息表里就是B卡,A卡的信息将不存在,换卡记录表里会有记录的(旧卡A,新卡B...),消费记录表里有A卡的消费记录也有B卡问题:怎么查询顾客的消费信息,将其用过的卡的消费记录汇总到一起(一个顾客可能经过多次换卡,还有的顾客A卡换成B卡,之后又B卡换A卡,换回来了)用游标的话  效率可能会有点低  如果记录多的话   求方法求帮助....

解决方案 »

  1.   

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

  2.   

    更正:;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.卡号
      

  3.   

     这个必须要排除那种A卡换B卡  B卡换A卡的现象  无限死循环
      

  4.   

    yes  我知道了  最后一个问题就是 死循环...
      

  5.   


    怎么将Cards这列修改为最大节点的newCard列的值  如图所示:将大方框的00001169改为小方框的00093617
      

  6.   

    ;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
      

  7.   


    Update a
    Set cards=b.newCard
    From [卡信息] As a
    Inner Join [卡信息] As b On a.cards=b.cards 
    And b.TransferDate=(select MAX(TransferDate) from [卡信息] As x
    Where x.cards=b.cards
    )