I have a table called Car:
CREATE TABLE [dbo].[Car](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Brand] [nchar](10) NOT NULL
)
and one called Passenger:
CREATE TABLE [dbo].[Passenger](
[ID] [int] IDENTITY(1,1) NOT NULL,
[CarID] [int] NOT NULL,
[Name] [nchar](10) NOT NULL
)
Containing the following data:
+----+------------+
| ID | Brand |
+----+------------+
| 1 | Ford |
| 2 | Audi |
+----+------------+
+----+-------+------------+
| ID | CarID | Name |
+----+-------+------------+
| 1 | 1 | Joe |
| 2 | 1 | Jack |
| 3 | 1 | Jim |
| 4 | 2 | Bob |
| 5 | 2 | Frank |
+----+-------+------------+
Also, I have a limit for the number of passengers in a car = 5. (Business logic)
What I'd like to do is to display this data in a View table, like the following example:
+----+------------+------------+------------+------------+------------+------------+
| ID | Brand | Passenger1 | Passenger2 | Passenger3 | Passenger4 | Passenger5 |
+----+------------+------------+------------+------------+------------+------------+
| 1 | Ford | Joe | Jack | Jim | NULL | NULL |
| 2 | Audi | Bob | Frank | NULL | NULL | NULL |
+----+------------+------------+------------+------------+------------+------------+
So, there if there are less than 5 passengers, the rest of the columns is NULL, and we don't need to handle more than 5 passengers.
Ordering of passengers is not really needed, but NULLs
must be at the end (e.g. Frank, Bob, NULL, NULL, NULL is OK for Car ID 2, but Frank, NULL, NULL, Bob, NULL
is not.) If it is also possible to order the passengers, then I'd prefer to order them by their IDs.
How can I do this data transformation using SQL Server 2012?