有几种方法可以解决这个问题。这是一个:
- 创建一个视图以合并表,为每个表添加适当的存档日期列
- 针对 EmployeeID 上的 Group 视图创建子查询并获取 MAX 存档日期
- 使用子查询加入视图,获取每个员工的最新记录
创建示例表架构和测试数据
SET NOCOUNT ON
IF OBJECT_ID('Employee', 'U') IS NOT NULL DROP TABLE Employee;
GO
IF OBJECT_ID('Employee2012Q1', 'U') IS NOT NULL DROP TABLE Employee2012Q1;
GO
IF OBJECT_ID('Employee2012Q2', 'U') IS NOT NULL DROP TABLE Employee2012Q2;
GO
CREATE TABLE dbo.Employee (
EmployeeID int IDENTITY(1,1) NOT NULL PRIMARY KEY
,EmployeeName varchar(50) NOT NULL
,StartDate smalldatetime NOT NULL
,EndDate smalldatetime NULL
,Salary decimal(18,2) NOT NULL
,Position varchar(50) NOT NULL
,HomeAddress varchar(200) NOT NULL
)
-- Employees hired
INSERT dbo.Employee SELECT 'John Doe', '01/01/2012', NULL, 50000, 'Developer', '12345 Main St, New York, NY'
INSERT dbo.Employee SELECT 'Jane Doe', '01/01/2012', NULL, 52000, 'Developer', '837 1st St, New York, NY'
-- Employee fired
UPDATE A
SET A.EndDate = '02/01/2012'
FROM dbo.Employee A
WHERE A.EmployeeName = 'John Doe'
-- Table archived
SELECT * INTO dbo.Employee2012Q1 FROM dbo.Employee
-- Remove fired employees
DELETE dbo.Employee WHERE EndDate IS NOT NULL
-- Employee hired
INSERT dbo.Employee SELECT 'Jack Flash', '04/01/2012', NULL, 73000, 'Manager', '9580 21st St, New York, NY'
-- Employee fired
UPDATE A
SET A.EndDate = '05/01/2012'
FROM dbo.Employee A
WHERE A.EmployeeName = 'Jack Flash'
-- Table archived
SELECT * INTO dbo.Employee2012Q2 FROM dbo.Employee
-- Remove fired employees
DELETE dbo.Employee WHERE EndDate IS NOT NULL
SET NOCOUNT OFF
GO
创建一个合并所有员工表的视图
IF OBJECT_ID('EmployeeArchive', 'V') IS NOT NULL DROP VIEW dbo.EmployeeArchive
GO
CREATE VIEW dbo.EmployeeArchive
AS
SELECT CONVERT(smalldatetime, CONVERT(char(10), GETDATE(), 101)) as [ArchiveDate]
,EmployeeID
,EmployeeName
,StartDate
,EndDate
,Salary
,Position
,HomeAddress
FROM dbo.Employee
UNION ALL
SELECT CONVERT(smalldatetime, '03/31/2012') as [ArchiveDate]
,EmployeeID
,EmployeeName
,StartDate
,EndDate
,Salary
,Position
,HomeAddress
FROM dbo.Employee2012Q1
UNION ALL
SELECT CONVERT(smalldatetime, '06/30/2012') as [ArchiveDate]
,EmployeeID
,EmployeeName
,StartDate
,EndDate
,Salary
,Position
,HomeAddress
FROM dbo.Employee2012Q2
GO
获取每位员工的最新信息
SELECT A.*
FROM dbo.EmployeeArchive A
JOIN (
SELECT EmployeeID, MAX(ArchiveDate) as MaxArchiveDate
FROM dbo.EmployeeArchive
GROUP BY EmployeeID
) B
ON A.EmployeeID = B.EmployeeID
AND A.ArchiveDate = B.MaxArchiveDate