我得到了所有员工的工作时间列表。查询在这里:
ALTER PROCEDURE [dbo].[Get_EmployeeWiseWorkingTime]
@PayPeriodID as int
AS
BEGIN
DECLARE @StartDate DATETIME='2014-04-21 00:00:00.000'
DECLARE @EndDate DATETIME='2014-05-04 00:00:00.000'
Select @StartDate=[PeriodStartDate],@EndDate=[PeriodEndDate] from PayPeriod --where PayPeriodId=@PayPeriodID
DECLARE @DateList VARCHAR(MAX), @DateListCoalesced VARCHAR(MAX)
SELECT @DateList = '', @DateListCoalesced = ''
;WITH DateLimits AS (
SELECT CAST(@StartDate AS DATE) AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM DateLimits s
WHERE DATEADD(dd, 1, dt) <= CAST(@EndDate AS DATE))
SELECT @DateList = @DateList + '[' + CAST(dt AS VARCHAR)+ '], ' ,
@DateListCoalesced = @DateListCoalesced + ' COALESCE( [' + CAST(dt AS VARCHAR)+ '] , 0) as [' + CAST(dt AS VARCHAR)+ '], '
FROM DateLimits
;SET @DateList = LEFT(@DateList, LEN(@DateList) - 1)
;SET @DateListCoalesced = LEFT(@DateListCoalesced, LEN(@DateListCoalesced) - 1)
DECLARE @query NVARCHAR(max)
SET @query = N'SELECT [EmployeeID],FirstName,LastName, ' + @DateListCoalesced +'
FROM
(SELECT DayLog.[EmployeeID],FirstName,LastName, DayLog.[CreatedDate], [WorkingTime]
FROM DayLog
INNER JOIN Employees ON Employees.EmployeeID = DayLog.EmployeeID
) p
PIVOT
(
Sum ([WorkingTime] )
FOR [CreatedDate] IN ( '+ @DateList +' )
) AS pvt order by EmployeeID'
EXEC sp_executesql @Query END
结果是:
我想添加一个列名总计,它会计算并添加所列数据的总工作时间。 任何例子都将不胜感激。
答案 0 :(得分:1)
;SET @DateList = @DateList + 'Total'
;SET @DateListCoalesced = @DateListCoalesced + 'Total'
SET @query = N'SELECT [EmployeeID],FirstName,LastName, ' + @DateListCoalesced +'
FROM
(
SELECT DayLog.[EmployeeID],FirstName,LastName, Convert(varchar(50), DayLog.[CreatedDate], 120) as CreatedDate, [WorkingTime]
FROM DayLog
INNER JOIN Employees ON Employees.EmployeeID = DayLog.EmployeeID
UNION
SELECT DayLog.[EmployeeID],FirstName,LastName, ''Total'', Sum([WorkingTime])
FROM DayLog
INNER JOIN Employees ON Employees.EmployeeID = DayLog.EmployeeID
GROUP BY DayLog.[EmployeeID],FirstName,LastName
) p
PIVOT
(
Sum ([WorkingTime] )
FOR [CreatedDate] IN ( '+ @DateList +' )
) AS pvt order by EmployeeID'