几天前我在SQL Server中处理了一个存储过程。我创建了这个存储过程代码:
ALTER procedure [dbo].[GetEmployeeHours]
(@CurrentDate datetime)
as
begin
declare @StartDate datetime
declare @EndDate datetime
set @StartDate = DATEADD(DAY, 1 - DATEPART(WEEKDAY, @CurrentDate), CAST(@CurrentDate AS DATE))
set @EndDate = DATEADD(DAY, 7 - DATEPART(WEEKDAY, @CurrentDate), CAST(@CurrentDate AS DATE))
--select @StartDate
--select @EndDate
SELECT
CASE WHEN
GROUPING(a.firstname +' '+a.lastname)=1
THEN 'Total By Day'
ELSE
a.firstname +' '+a.lastname
END AS [EmployeeName] ,
SUM(CASE WHEN datename(dw,workdate)='Monday' THEN [hours] ELSE 0 END) AS Monday,
SUM(CASE WHEN datename(dw,workdate)='Tuesday' THEN [hours] ELSE 0 END) as Tuesday,
SUM(CASE WHEN datename(dw,workdate)='Wednesday' THEN [hours] ELSE 0 END) as WEDNESDAY,
SUM(CASE WHEN datename(dw,workdate)='Thursday' THEN [hours] ELSE 0 END) as THURSDAY,
SUM(CASE WHEN datename(dw,workdate)='Friday' THEN [hours] ELSE 0 END) as FRIDAY,
SUM(CASE WHEN datename(dw,workdate)='Saturday' THEN [hours] ELSE 0 END) as SATURDAY,
SUM(CASE WHEN datename(dw,workdate)='Sunday' THEN [hours] ELSE 0 END) as SUNDAY,
SUM(hours) AS [TotalHours]
FROM Project_TimeSheet b inner join Project_Employee a on b.employeeid =a.id
WHERE workdate >= @StartDate and workdate<= @EndDate
GROUP BY a.firstname +' '+a.lastname
WITH ROLLUP
end
在这个存储过程中,我得到每天的结果,并将周名称作为列名。首先,我想使用数据透视表,但我在堆栈溢出时发现了这一点,所以我使用它。现在我想在星期名称的位置显示日期作为列名。有人可以告诉我怎么办?我尝试通过声明变量来分配值,但所有这些都不起作用
由于
答案 0 :(得分:0)
您需要使用动态SQL。如果您查找动态数据透视的示例,您将快速找到代码。但要注意,因为消耗结果的应用程序需要足够聪明才能发现列名...