在SQL Server中需要有关Pivot的帮助

时间:2017-06-24 20:59:02

标签: sql sql-server tsql

需要关于枢轴的帮助..我的i / p和o / p如下(请参阅附图)..请你帮我查询... enter image description here

2 个答案:

答案 0 :(得分:1)

这里创建了获取结果的样本数据

IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
;WIth cte(EmployeeID, Activity_Date,Activity_Type)
AS
(
SELECT 1,'6/20/2016' ,'Mail_send'       UNION ALL
SELECT 2,'6/22/2011' ,'Mail_Received'   UNION ALL
SELECT 1,'10/11/2016','Mail_Replied'    UNION ALL
SELECT 3,'10/31/2016','Mail_deleted'    UNION ALL
SELECT 2,'2/11/2016' ,'Mail_Forwared'
)

SELECT * INTO  #Temp FROM cte

我们可以通过使用带有Pivot的动态Sql来获得结果

DECLARE @dynamicCol nvarchar(max),
        @Sql nvarchar(max)


SELECT @dynamicCol=STUFF((SELECT DISTINCT ', ' +QUOTENAME(Activity_Type)  FROM  #Temp
FOR XML PATH('')),1,1,'')

SET @Sql='
            SELECT  [EmployeeID] , '+ @dynamicCol +' From
            (
            SELECT * From
            #temp
            )AS Src
            PIVOT 
            (
            MAX([Activity_Date]) For [Activity_Type] IN ('+@dynamicCol+')
            )
            AS Pvt
            '

PRINT @Sql

EXEC(@Sql)

结果

EmployeeID  Mail_deleted    Mail_Forwared   Mail_Received   Mail_Replied    Mail_send
--------------------------------------------------------------------------------------
1           NULL            NULL            NULL            10/11/2016      6/20/2016
2           NULL            2/11/2016       6/22/2011       NULL            NULL
3           10/31/2016      NULL            NULL            NULL            NULL

答案 1 :(得分:0)

尝试以下查询,这应该符合您的目的:

select * from
(select [Employee Id],Activity_Date,Activity_Type from Employee_Activity) tbl
pivot
(
max(Activity_Date) for Activity_Type in (Mail_Send,Mail_Received,Mail_Replied,Mail_deleted,Mail_Forwarded)
)as pvt