
That is my table #EmployeeTemp.
What I would like to do is retrieving data like that below.

So first of all, I use below query to retrieve data as I want.
CREATE TABLE #EmployeeTemp
(Employee_Name VARCHAR(50),
Confirmed_Date DATETIME,
Field_Type VARCHAR(50),
Field_Value VARCHAR(50))
INSERT INTO #EmployeeTemp VALUES ('John', '2009/1/1', 'Title', 'Programmer');
INSERT INTO #EmployeeTemp VALUES ('John', '2009/1/1', 'Department', 'IT Department');
INSERT INTO #EmployeeTemp VALUES ('John', '2011/1/1', 'Title', 'Sr. Programmer');
INSERT INTO #EmployeeTemp VALUES ('David', '2010/1/1', 'Title', 'Software Engineer');
INSERT INTO #EmployeeTemp VALUES ('David', '2010/1/1', 'Department', 'IT Department');
SELECT * FROM #EmployeeTemp
SELECT
MyEmployee.Confirmed_Date,
MyEmployee.Employee_Name,
Title = MAX(MyEmployee.Field_Value),
Department = (SELECT
Field_Value
FROM #EmployeeTemp
WHERE Field_Type = 'Department'
AND Employee_Name = MyEmployee.Employee_Name
GROUP BY Employee_Name, Field_Value)
FROM #EmployeeTemp AS MyEmployee
WHERE MyEmployee.Confirmed_Date IN (SELECT MAX(Confirmed_Date) FROM #EmployeeTemp GROUP BY Employee_Name)
GROUP BY MyEmployee.Employee_Name, MyEmployee.Confirmed_Date
ORDER BY MyEmployee.Confirmed_Date DESC
It worked as I wanted. But what I would like to ask is could you please give me any suggestion to write query more professional way.
Every suggestion will be appreciated.
I am using Microsoft SQL Server 2008 version.
This question is very subjective, so what in my opinion is a more elegant solution, may be a less elegant solution in someone else’s opinion. However, this is the approach I would adopt, using the SQL-Server PIVOT Functionality.
The reason I prefer this approach is firstly it is less work on the server (when checking actual execution plans for your query compared to this one, this one had a cost of 27% relative to the batch, as opposed to the 73% cost of yours). Secondly, if you need to add more fields, it is simply a case of extending the following line:
e.g. with the following extra data:
you would only need to make the line:
to get the extra column required in the output.