I have a table that contains user information (UserInfo), and some users may be in the table twice under different UserIds, like so:
UserId LastName FirstName active
000001 Jetson George 1
000002 Flintstone Fred 0
000003 Jetson George 1
000004 Flintstone Fred 1
000005 Barbara Hannah 1
Only 1 row per user should show as active, but a bug in the application is causing there to be two user entries with unique UserIds that have active set to 1.
I then have another table that contains records associated with a UserId (UserRecords). In the case of duplicate active UserIds, only one of the two UserIds will return any results in the second table. Thus:
SELECT
((SELECT count(*)
FROM UserRecords recs
where recs.UserId= inf.UserId)) as Records, *
FROM UserInfo inf
where inf.lastname = 'Jetson' and
inf.active='1' and
inf.firstname='George'
might return:
Records UserId LastName FirstName active
0 000001 Jetson George 1
1273 000003 Jetson George 1
I want to create an update statement to change the active column to 0 for any entries where active = '1' and Records='0'
, but there are hundreds of users that have duplicate entries, and there could be more later. So I would like to create an update statement that would find these and set them to 0 automatically.
What I have is
update UserId
set active = '0'
where (SELECT count(*)
FROM UserRecords recs
where recs.UserId= inf.UserId) = 0
The problem with that statement is that it does not take into account duplicate users. There could be users who simply have no records in UserRecords (yet) but that also do not have duplicate entries. Setting those to 0 would cause system problems.
So, how can I change my update statement to only mark active as 0 where there are duplicate entries?
Any help would be greatly appreciated.
Thanks!