--id是本人的卡,oldid是转账人的卡,moneynum是转账(充值)的金额
create table tb(id int,oldid int,moneynum money)
insert into tb
select 1,null, 3
union all select 2,1,1.00
union all select 3,1,6.00
union all select 4,2,5.00
union all select 5,4,3.00
union all select 3,4,7.00
union all select 4,null,8.00
union all select 7,6,2.00
union all select 8,7,3.00
union all select 1,10,7.00
union all select 10,null,7.00
oldid为null的数据,说明是充值,如果oldid不为空,说明是别人转账过来的
我现在的目的是求转账信息,而且得找到底
比如我找卡号为5的,结果是:
id,oldid,moneynum
1,10,7.00
2,1,1.00
4,2,5.00
5,4,3.00
卡号10没人转钱给他,就只找到卡号1
如果找卡号8,要求的结果是:
id,oldid,moneynum
7,6,2.00
8,7,3.00

解决方案 »

  1.   

    use test
    go
    if object_id('test.dbo.tb') is not null drop table tb
    -- 创建数据表
    create table tb(id int,oldid int,moneynum money)
    insert into tb
    select 1,null, 3
    union all select 2,1,1.00
    union all select 3,1,6.00
    union all select 4,2,5.00
    union all select 5,4,3.00
    union all select 3,4,7.00
    union all select 4,null,8.00
    union all select 7,6,2.00
    union all select 8,7,3.00
    union all select 1,10,7.00
    union all select 10,null,7.00
    --代码实现;with t as(
    select * from tb where id=5
    union all
    select a.* from tb a join t b on a.id=b.oldid and a.oldid is not null
    )
    select * from t order by id/*测试结果id  oldid moneynum
    ----------------------------
    1 10 7.00
    2 1 1.00
    4 2 5.00
    5 4 3.00(4 行受影响)
    */
      

  2.   

    不知道不用1楼的方法还有什么好的方法呢?2000没有with
      

  3.   

    不能order by id
    这个测试数据恰好是递增的,如果前面有条10,11,8.00的数据呢?
    其实我的意思很明显
    就是按资金的流转排列10转给1,1转给2,2转给4,4转给5->显示结束
    不能投机取巧的order by id