It's difficult for me...
I am working on Microsoft SQL Server 2008, and I have a table with usernames in it. The names of people could change over time, so there is historical information.
Example:
PID Sequence Name 1 0 Michael Hansen 2 0 Ulla Hansen 2 94 Ulla Margrethe Hansen 2 95 Ulla Margrethe Jensen 3 0 Daniella Oldfield 3 95 Daniella Quist
(I did not create this table, so I cannot log in and change the way data is stored). The person with PID 1 is called Michael Hansen. This is his current name (sequence 0 always indicates the current name), and since there are no other entries, he was always called Michael Hansen.
Person PID 2 is currently called Ulla Hansen (sequence 0). Before that, she was called Ulla Margret Hansen (since this is the next serial number), and before that she was again called Ulla Margret Jensen.
What I know about this table is that the current name is always sequence 0. I also know that if there were two names, the next sequence is 95. And three historical names: current name: sequence 0, before this sequence 94 and the oldest name 95.
And my database contains information on six historical names (sequences 0, 91, 92, 93, 94, 95).
Now I was told to list all the names in the new table with only one row per person, for example:
PID Name1 Name2 Name3 1 Michael Hansen 2 Ulla Hansen Ulla Margrethe Hansen Ulla Margrethe Jensen 3 Daniella Oldfield Daniella Quist
So far, I have the following SQL that almost works:
SELECT PID ,MAX(CASE sequence WHEN 0 THEN Name ELSE '' END) AS Name1 ,MAX(CASE sequence WHEN 91 THEN Name ELSE '' END) AS Name2 ,MAX(CASE sequence WHEN 92 THEN Name ELSE '' END) AS Name3 ,MAX(CASE sequence WHEN 93 THEN Name ELSE '' END) AS Name4 ,MAX(CASE sequence WHEN 94 THEN Name ELSE '' END) AS Name5 ,MAX(CASE sequence WHEN 95 THEN Name ELSE '' END) AS Name6 FROM tblShipTypeHistory GROUP BY PID
He gives me all the names since I want them on the same line on the PID. And the current name is also always displayed under Name1. The problem is that I need the middle name to be in the column Name2, etc. In my case (of course), I only work if the person had six names.
So what I need to do is name the columns Name2 to Name6 dynamically based on how many names the PID actually had. So I tried to build my SQL dynamically like (DECLARE @SQL AS NVARCHAR (MAX), and then set @SQL = to the SQL example above). Then I tried something like
SET @SQL = 'SELECT .... ,MAX(CASE sequence WHEN 91 THEN Name ELSE '' END) AS Name' + COUNT(PID) - 4 + ' ,MAX(CASE sequence WHEN 92 THEN Name ELSE '' END) AS Name' + COUNT(PID) - 3 + ' ,MAX(CASE sequence WHEN 93 THEN Name ELSE '' END) AS Name' + COUNT(PID) - 2 + ' ,MAX(CASE sequence WHEN 94 THEN Name ELSE '' END) AS Name' + COUNT(PID) - 1 + ' ,MAX(CASE sequence WHEN 95 THEN Name ELSE '' END) AS Name' + COUNT(PID) + '
Logically this can work (it will give the correct column names), but, unfortunately, the syntax "+ count (PID)" does not work.
(Fu!) So, who has a solution for this?
Thanks in advance.