那是我的桌子#EmployeeTemp
。
我想做的是检索如下数据。
所以首先,我使用下面的查询来检索我想要的数据。
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
它按我的意愿工作。但我想问的是,您能否给我任何建议以更专业的方式编写查询。
每一个建议都将不胜感激。
我使用的是 Microsoft SQL Server 2008 版本。