如果你可以帮我在SQL表中将Column转换为Rows,那就太棒了。
假设我有3列名为:
目前它出现了这样:
我希望看起来像这样 - Result Table
这是我写的一个查询,但仍然是错误:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(shift_date)
from dbo.tbl_Multi_Shift_Employee WHERE Shift_Date BETWEEN CONVERT(DATE, '01/02/2018 00:00:00',103) AND CONVERT(DATE, '28/02/2018 00:00:00',103)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Employee_ID, total, Department_ID, shift_id, ' + @cols + ' from
(
select count(*) over(partition by t.Employee_ID) total,
s.Department_ID,
t.Employee_ID,
t.shift_id
from dbo.tbl_Multi_Shift_Employee t
inner join dbo.tbl_department s
on t.Department_ID = s.Department_ID
) x
pivot
(
count(shift_id)
for shift_id in (' + @cols + ')
) p '
PRINT @query
execute(@query)
答案 0 :(得分:0)
首先,你必须从主要选择中移除shift_id,因为它被用作枢轴。 其次,使用shift_date更改shift_id,这是您用作枢轴列的正确列。
ls -la