I have a table with few columns say,
FirstName, Lastname, Phonenumber, Accesslevel
AA , BB , +447000000000, AL1
CC , DD , +447800000000 , AL2
AA , BB , +447000000000 , AL3
If the phoneNumbers and Lastname are same, I want the below results (I mean I need to Update the table instead of just select)
FirstName, Lastname, Phonenumber, Accesslevel
AA , BB , +447000000000, AL1, AL3
CC , DD , +447800000000 , AL2
AA , BB , +447000000000 , AL3
The script I have doesn't do what i Want,
UPDATE [dbo].[Table]
SET [AccessLevel] = stuff ( ( SELECT
', ' + [ExtAccessLevelIDList]
FROM
[Table] t1
where t1.PhoneNumber = t2.PhoneNumber
FOR XML PATH ( '' ) ) , 1 , 1, '' )
from [Table] t2```
Well, if you care about both the telephone number and name, you need equality on both those columns:
UPDATE t2
SET [AccessLevel] = STUFF( (SELECT ', ' + [ExtAccessLevelIDList]
FROM [Table] t1
WHERE t1.PhoneNumber = t2.PhoneNumber AND
t1.LastName = t2.LastName
FOR XML PATH ( '' )
), 1, 2, ''
)
FROM (SELECT t2.*,
ROW_NUMBER() OVER (PARTITION BY LastName, PhoneNumber ORDER BY (SELECT NULL)) as seqnum
FROM [Table] t2
) t2
WHERE seqnum = 1;
Note:
More recent versions of SQL Server support string_agg()
which makes this much simpler:
update [table]
set AccessLevel = tt.accesslevel
from (select phonenumber, lastname,
string_agg(ExtAccessLevelIDList, ', ') as accesslevel
from [table]
group by phonenumber, lastname
) tt
where tt.phonenumber = [table].phonenumber and
tt.lsatname = [table].lastname;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.