I’ve got a SQL table similar to this:
+-----------------------------------------------+
| ID | FirstName | LastName | SomeOtherData|
+-----------------------------------------------+
| 200 | Robert | Barone | Foo |
| 228 | Doug | Heffernan | Bar |
| 2091 | Robert | Barone | Foo |
| 3921 | Doug | Heffernan | Bar |
| 291 | Greg | Warner | Barfoo |
+-----------------------------------------------+
Now what I’m having trouble producing is a table that’ll list both IDs for a given Person, assuming that FirstName and LastName are used to indicate duplicates. So, basically I’m trying to get:
+---------------------------------------------------------+
| ID | OtherID | FirstName | LastName | SomeOtherData|
+---------------------------------------------------------+
| 200 | 2091 | Robert | Barone | Foo |
| 228 | 3921 | Doug | Heffernan | Bar |
| 291 | | Greg | Warner | Barfoo |
+---------------------------------------------------------+
Would anyone be able to help me out with something like this? Thanks!
You can use a
PIVOTwhich will transform the data from rows into columns:See SQL Fiddle with Demo
Or you could use an aggregate function with a
CASEexpression:The above will work great if you have a known number of duplicate values (1, 2, etc). You could also implement dynamic SQL if you have more than 2 id’s. The dynamic SQL would look like:
See SQL Fiddle with Demo
The result of all 3 would be: