Search code examples
sqlsql-servert-sqlsql-query-store

how to select the second row if the first row in empty


how to select the second row in Sql server query if the first row is empty. I have 3 tables

  1. Users
  2. sites
  3. siteUser

A user can be assigned to multiple sites and a site can have multiple users but now i want to get only one user for each site but if the first user doesn't have a mobile number that start with +01 i have to get the second user assigned to that site but him also if he doesn't have i have to select the 3rd. please help


Solution

  • This query gives first registered user with phone number starts with +01 for each site

    select s.name, u.*
    from site s
    outer apply (
                    select top(1) * 
                        from user u 
                        where u.phone like '+01%' 
                        and u.id in (select userId FROM siteUser su WHERE su.SiteId = s.Id)
                        order by u.registrationDate
                ) as u