I have two tables in my SQL Server db that I want to join:
Person table:
PersonId Name DeviceId
001 John 11111
002 Eric 22222
003 Steve 33333
Device Table:
DeviceId Date
11111 2013-02-01
11111 2013-02-02
11111 2013-02-03
22222 2013-02-03
22222 2013-02-01
The result I want is the following
PersonId Name DeviceId Date IsRegistered
001 John 11111 2013-02-03 1
002 Eric 22222 2013-02-03 1
003 Steve 33333 null 0
So as you see I want a join between the tables and I only want unique values.
The data field should be the last registered (newest date). If the person has a value in the date field the IsRegistered
should have value 0
If anyone know how I can fix this I would appreciate it
Query:
I see that you also need
isRegistered
column, here it is:Query:
Results:
Try this:
SQL Fiddle Demo
This will give you:
Or: Using the ranking function
ROW_NUMBER()
you can do this:Updated SQL Fiddle Demo
This will give you the same result.