I have Table A. How can I select from Table A to get Table B Format?
Table A
Employee Name Effective Date FieldType FieldValue
Maung Mya 1/1/2005 Title Project Engineer
Maung Mya 1/1/2005 Department IT Department
Maung Mya 1/1/2007 Title 开发者_运维问答Assist Project Manager
Kyaw Kyaw 1/1/2006 Title Software Engineer
Kyaw Kyaw 1/1/2006 Department IT Department
Table B
Effective Date Employee Name Title Department
1/1/2007 Maung Mya Assist Project Manager IT Department
1/1/2006 Kyaw Kyaw Software Engineer IT Department
It looks like you want something like this:
SELECT A.[Effective Date],
A.[Employee Name],
A.FieldValue AS Title,
A2.FieldValue AS Department
FROM A INNER JOIN
A AS A2
ON A.[Employee Name] = A2.[Employee Name] AND
A.[Effective Date] = A2.[Effective Date] AND
A.FieldType = 'Title' AND
A2.FieldType = 'Department'
WHERE A.[Effective Date] = (
SELECT MAX([Effective Date])
FROM A AS A3
WHERE A3.[Employee Name] = A.[Employee Name] AND A3.FieldType = 'Title')
AND A2.[Effective Date] = (
SELECT MAX([Effective Date])
FROM A AS A4
WHERE A4.[Employee Name] = A2.[Employee Name] AND A3.FieldType = 'Department')
EDIT: RedsDevils I have edited my code and tested it using your example. This should work now
Bearing in mind that the same employee might change department, or get a promotion through his career, my two joins look for the latest Effective Date for each type.
SELECT derived.[Effective Date],
derived.[Employee Name],
title1.[FieldValue] AS Title,
dept1.[FieldValue] AS Department
FROM
(
SELECT MAX([Effective Date]) AS [Effective Date], [Employee Name]
FROM TableA
GROUP BY [Employee Name]
) derived
-- Inner Join for TITLE
INNER JOIN TableA title1 ON derived.[Employee Name] = title1.[Employee Name]
AND title1.FieldType = 'Title'
AND title1.[Effective Date] = (SELECT MAX(title2.[Effective Date])
FROM TableA title2
WHERE title1.[Employee Name] = title2.[Employee Name]
AND title2.FieldType = 'Title')
-- Inner Join for DEPARTMENT
INNER JOIN TableA dept1 ON derived.[Employee Name] = dept1.[Employee Name]
AND dept1.FieldType = 'Department'
AND dept1.[Effective Date] = (SELECT MAX(dept2.[Effective Date])
FROM TableA dept2
WHERE dept1.[Employee Name] = dept2.[Employee Name]
AND dept2.FieldType = 'Department')
I created a derived table first to get the MAX Effective Date and Employee Name, and aliases it with the name 'derived'. I then created to join to get the last know Title and Department.
Yes, I got it! Based on Gabe's answer, I can retrieve the format I want and only 2 records. Thanks all! The answer is as follows.
SELECT TableA.[Effective Date], TableA.[Employee Name], TableA.FieldValue AS Title,A2.FieldValue AS Department FROM TableA INNER JOIN TableA AS A2 ON TableA.[EmployeeName] = A2.[EmployeeName] AND TableA.[EffectiveDate] = (SELECT MAX([EffectiveDate]) FROM TableA AS A3 WHERE A3.[EmployeeName] = TableA.[EmployeeName] AND A3.FieldType = 'Title') AND TableA.FieldType = 'Title' AND A2.FieldType = 'Department'
精彩评论