2021-01-28

SQL Getting unique list and replace nulls

I am working on some data that is structured like this

userid useremail username sessionId eventTime
joe 1 2021-01-27 21:03:03.2500000
123 joe@me.com 1 2021-01-27 21:05:03.2500000
123 joe@me.com joe 1 2021-01-27 21:03:03.2500000
joe@me.com 2 2021-01-26 21:05:03.2500000
123 joe@me.com joe 2 2021-01-26 21:03:03.2500000
123 joe 2 2021-01-26 21:05:03.2500000
joe@me.com joe 2 2021-01-26 21:03:03.2500000
123 2 2021-01-26 21:05:03.2500000

So basically userid, usermail, or username can be blank, but sessionId is always populated. I want to be able to get a result set that has each row, but with the missing fields populated. I can assume at least one of the 3 user fields is populated, otherwise I don't care.

Like this

userid useremail username sessionId eventTime
123 joe@me.com joe 1 2021-01-27 21:03:03.2500000
123 joe@me.com joe 1 2021-01-27 21:05:03.2500000
123 joe@me.com joe 1 2021-01-27 21:03:03.2500000
123 joe@me.com joe 2 2021-01-26 21:05:03.2500000
123 joe@me.com joe 2 2021-01-26 21:03:03.2500000
123 joe@me.com joe 2 2021-01-26 21:05:03.2500000
123 joe@me.com joe 2 2021-01-26 21:03:03.2500000
123 joe@me.com joe 2 2021-01-26 21:05:03.2500000

I have tried a few different subselects and inner-joins, but I am not able to get a result with all 3 populated. I can provide more sample data if needed

Things I have tried

 select a.userEmail, b.*
from (
select *
  from PageViewsTable
    and userEmail is not null
) a join (
  select *
  from PageViewsTable
    and userEmail is null
) b on a.sessionId = b.sessionId


select
  (SELECT top 1
    userEmail
  FROM PageViewsTable b
  WHERE a.sessionId = b.sessionId ) as email
  , *
from PageViewsTable a


from Recent Questions - Stack Overflow https://ift.tt/3co7vhf
https://ift.tt/eA8V8J

No comments:

Post a Comment