现在两表结构如下:
表信息:select * from Client_Linfo  --资金账号表
主要字段:[Fundaccount]        资金账号
[Opendate]            开户时间
 select * from USR_VIRUSER --手机登陆信息表主要字段:
USR_CUSTID                资金账号
USR_VUSER_MOBILE      登陆手机号码
INSERTDATE                登陆时间
 
问题解说:资金帐号与手机号为多对多关系,即一个资金帐号可以在多个人的手机上登录,一个手机可以登录多个资金帐号。现要求一SQL判断资金帐号和手机帐号第一次出现的的记录为有效记录;
例:
资金帐号A       手机1
资金帐号B       手机2
资金帐号C       手机3
帐号A可以对应所有手机(帐号B、C类似),假如第一次是用手机1(也可是手机2、3)登录帐号A,故帐号A对应手机1为有效记录,其它的不记。
如现在帐号B也在手机1上登录了,但因手机1已经登录过帐号A,记录已经存在。这样的记录无效。
 
救解,有不清楚的尽管问我。 

解决方案 »

  1.   

    select USR_CUSTID,USR_VUSER_MOBILE,INSERTDATE
    from (
    select *,r1=row_number() over(partition by USR_CUSTID order by INSERTDATE),
    r2=row_number() over(partition by USR_VUSER_MOBILE order by INSERTDATE)
    from USR_VIRUSER ) k
    where k.r1=1 or k.r2=1
      

  2.   

    create table #Client_Linfo([Fundaccount] varchar(100), [Opendate] datetime)
    insert #Client_Linfo
    select 'a0001', GETDATE() union all
    select 'b0001', GETDATE()
    create table #USR_VIRUSER(USR_CUSTID varchar(100), USR_VUSER_MOBILE varchar(100), INSERTDATE datetime)
    insert #USR_VIRUSER
    select 'a0001', '130xxxx1234', GETDATE()-1 union all
    select 'a0001', '130xxxx1235', GETDATE() union all
    select 'b0001', '130xxxx1234', GETDATE()+1 union all
    select 'b0001', '130xxxx1235', GETDATE()+2
    go--用游标很好理解,用SQL,期待高手……
    declare @Fundaccount varchar(100)
    declare @USR_VUSER_MOBILE varchar(100)
    declare @table table
    (
    [Fundaccount] varchar(100),
    USR_VUSER_MOBILE varchar(100)
    )
    declare cur cursor local static read_only for
    select [Fundaccount] from #Client_Linfo order by Opendate
    open cur
    fetch next from cur into @Fundaccount
    while @@FETCH_STATUS = 0
    begin
    set @USR_VUSER_MOBILE = ''
    select top(1) @USR_VUSER_MOBILE = USR_VUSER_MOBILE from #USR_VIRUSER t
    where USR_CUSTID = @Fundaccount and not exists(select 1 from @table where USR_VUSER_MOBILE = t.USR_VUSER_MOBILE)
    insert into @table values(@Fundaccount, @USR_VUSER_MOBILE)
    fetch next from cur into @Fundaccount
    end
    close cur
    DEALLOCATE curselect * from @table
    /*
    Fundaccount USR_VUSER_MOBILE
    a0001 130xxxx1234
    b0001 130xxxx1235
    */