SQL Server row values as column names Pivot Table?

2019-02-20 10:36发布

I have the following view in SQL Server 2008.

DEPT | EMP_ID | EMP_NAME | P_DATE  | HOURS_WORKED

I want the view to be this way:

DEPT | EMP_ID | EMP_NAME | 2012-09-28 | 2012-09-29 | 2012-09-30 | 2012-10-01 ...

where the above date column header is P_DATE below which is "Hours_Worked" values of that employee on that particular date.

Like

2012-09-28

09:00:00

10:00:00

I am not sure whether I could achieve it using Pivot.

Please go to this link for clear understanding : SQL Server View Snapshots

1条回答
可以哭但决不认输i
2楼-- · 2019-02-20 11:15

You can perform this with the PIVOT function. If you know the values that you want to turn into columns than you can hard code then using a static pivot:

select *
from 
(
  select dept, emp_id, emp_name, p_date, hours_worked
  from table1
) x
pivot
(
  max(hours_worked)
  for p_date in ([2012-10-19], [2012-10-20], [2012-10-21])
) p

See SQL Fiddle with Demo

If you have an unknown number of values, then you can use dynamic sql to PIVOT the data:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' 
                        + QUOTENAME(convert(char(10), p_date, 120)) 
                    from table1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT dept, emp_id, emp_name,' + @cols + ' from 
             (
                select dept, emp_id, emp_name, p_date, hours_worked
                from table1
            ) x
            pivot 
            (
                max(hours_worked)
                for p_date in (' + @cols + ')
            ) p '

execute(@query)

See SQL Fiddle with Demo

查看更多
登录 后发表回答