如何将给定的SQL记录填充到所有UserID

时间:2018-03-05 10:05:57

标签: sql sql-server

我有一张表格:

id | firstname | lastname | userid
---+-----------+------------------------
1  | john      | smith    | 545868-5434-343435-35353
2  | adam      | finger   | 545868-5434-343435-35353
3  | teri      | marti    | 545868-5434-343435-35353
4  | pei       | port     | 545868-5434-343435-35353

在数据库中我有很多userid我需要填充与firstname lastname完全相同的useridDatabase >

这是我的SQl查询

SELECT  

cID, c.firstname,c.lastname,

[s].UserID,c.OwnerID

FROM  
Customer INNER JOIN [s] ON c.OwnerID = [s].UserID AND c.AssignedtoID =
[s].UserID AND c.CreatedByUserID = [s].UserID

AssignedtoID与UserID

相同

2 个答案:

答案 0 :(得分:0)

这对你有帮助。?

    Create table #tmpCustomer (id int, firstname VARCHAR(50),lastname VARCHAR(50),userid VARCHAR(100))


    INSERT INTO #tmpCustomer 
    SELECT 1, 'john','smith','545868-5434-343435-35353'
    union
    SELECT 2,'adam','finger','545868-5434-343435-35353'
    union
    SELECT 3,'teri','marti','545868-5434-343435-35353'
    union
    SELECT 4, 'pei','port','545868-5434-343435-35353'
    union
    SELECT 5, 'abc','xyz','545868-5434-343435-35354'
    union
    SELECT 6, 'mno','ert','545868-5434-343435-35354'


    --select * from #tmpCustomer

    ;with cte1 AS(Select row_number()over(partition by userid order by id) rn,* from #tmpCustomer ),
          cte2 AS (select * from cte1 where rn=1 ) 

    update t
    set t.firstname=c.firstname
    from #tmpCustomer t
    JOIN cte2 c on t.userid=c.userid 

    select * from #tmpCustomer

    drop table #tmpCustomer

答案 1 :(得分:0)

我不知道我是否理解您的问题,请尝试下面的解决方案

DECLARE @cust as table(firstname varchar(20),lastname varchar(20))

插入@cust 值 ('苏珊''史密斯&#39)

将@id声明为表(id int identity,任何varchar(20),row_inserted datetime2 default(cast(sysdatetime()as datetime2)))

INSERT @id (任何,row_inserted)

SELECT' x' ' 20180305' 联合所有 选择' y' 20180305' 联合所有 选择'' 20180305'

选择s.id,c.firstname, c.lastname 来自@id as s 交叉加入@cust as c