数据透视表 - 将数据行数据到列

时间:2015-08-31 09:36:43

标签: sql tsql pivot pivot-table dynamic-columns

我有一个SQL表来存储员工的出勤率(打卡和打卡),我目前正在努力将每天的总工作时间存储在表格中(总天数最多约为22到30天) .. 存储的数据如下:

ID  date        time        Status
1   01/08/2015  08:00 AM    IN
1   01/08/2015  01:00 PM    OUT
1   01/08/2015  02:30 PM    IN
1   01/08/2015  07:30 PM    OUT
1   02/08/2015  11:00 AM    IN
1   02/08/2015  06:00 PM    OUT
1   02/08/2015  09:30 PM    IN
1   03/08/2015  02:30 AM    OUT
1   03/08/2015  08:00 AM    IN
1   03/08/2015  06:00 PM    OUT
1   04/08/2015  08:00 AM    IN
1   04/08/2015  06:00 PM    OUT

现在我希望数据如下所示:

ID  01/08/2015  02/08/2015  03/08/2015  04/08/2015  total
1       10          12          10          10      42
2       9           10          10          11      40

我已经阅读了很多关于数据透视表的文章,但是它们都使用了特定数量的列,所以如何动态地解决它?

1 个答案:

答案 0 :(得分:2)

DECLARE @cols AS VARCHAR(MAX)
DECLARE @query  AS VARCHAR(MAX)

select  @cols = STUFF((SELECT ',' + QUOTENAME( cast(CONVERT( VARCHAR(20), Edate,103 ) as varchar(10)))   
                    from   
                    (  
                     select a1.Edate from (
                        SELECT DISTINCT   Edate 
                        from InOut  
                      )a1

                    ) t  

            FOR XML PATH(''), TYPE  
            ).value('.', 'VARCHAR(MAX)')   
        ,1,1,'')  

    EXEC( ' SELECT Id,' + @cols + '    
            from   
            (  
              select Id,
                 Edate ,  
                status
              from  
              (  
                select convert(varchar(20), Edate,103)Edate, Id,status
                from InOut
              ) src  
            ) x  
            pivot   
            (  
                count(status)  
                for Edate in (' + @cols + ')  
            ) p where 1=1 ')