SQL Server SELECT查询,行数据转换为PIVOT等列转换

时间:2012-05-08 07:25:10

标签: sql sql-server sql-server-2008 tsql pivot

My Current in used Table

这是我的表#EmployeeTemp

我想要检索的数据如下所示。

To display like that style

首先,我使用下面的查询来检索我想要的数据。

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版本。

1 个答案:

答案 0 :(得分:2)

这个问题非常主观,所以我认为更优雅的解决方案,可能是别人看来不太优雅的解决方案。但是,这是我将采用的方法,使用SQL-Server PIVOT功能。

;WITH Employees AS
(   SELECT  *, 
            MAX(Confirmed_Date) OVER(PARTITION BY Employee_Name, Field_Type) [MaxFieldConfirmedDate],
            MAX(Confirmed_Date) OVER(PARTITION BY Employee_Name) [MaxConfirmedDate]
    FROM    #EmployeeTemp
)
SELECT  *
FROM    (   SELECT  MaxConfirmedDate [Confirmed_Date], Employee_name, Field_Type, Field_Value
            FROM    Employees
            WHERE   Confirmed_Date = MaxFieldConfirmedDate
        ) data
        PIVOT
        (   MAX(Field_Value)
            FOR Field_Type IN ([Title], [Department])
        ) Pvt

我更喜欢这种方法的原因首先是它在服务器上的工作量较少(当检查查询的实际执行计划时,与此相比,这个相对于批处理的成本为27%,而不是73你的成本百分比)。其次,如果您需要添加更多字段,则只需扩展以下行:

FOR Field_Type IN ([Title], [Department])

e.g。以下额外数据:

INSERT INTO #EmployeeTemp VALUES ('John', '2011/1/1', 'Test', 'Test');
INSERT INTO #EmployeeTemp VALUES ('David', '2010/1/1', 'Test', 'Test');

你只需要排队:

FOR Field_Type IN ([Title], [Department], [Test])

获取输出中所需的额外列。