如何在Tsql中按周计算员工的工作时间

时间:2016-09-16 13:50:09

标签: tsql

如何按周计算员工的总工时。

employee    week1   week2   week3   week4
rams         50      48       49     54

2 个答案:

答案 0 :(得分:0)

不知道你的表的结构会让它变得困难但如果它与下面的类似:那么你可以使用带有动态sql的pivot:

DECLARE @dynamicSql AS nvarchar(max)
DECLARE @dynamicCols AS nvarchar(max);


IF OBJECT_ID('tempdb..#tempHours') IS NOT NULL
DROP TABLE #tempHours

CREATE TABLE #tempHours (
  empId int,
  workDate datetime,
  hoursWorked money
)

INSERT INTO #temphours
  VALUES (1, '1/2/2016', 8.5)
INSERT INTO #temphours
  VALUES (2, '2/3/2016', 8.5)
INSERT INTO #temphours
  VALUES (3, '3/4/2016', 8.5)
INSERT INTO #temphours
  VALUES (4, '4/5/2016', 8.5)
INSERT INTO #temphours
  VALUES (5, '5/6/2016', 8.5)

INSERT INTO #temphours
  VALUES (1, '1/3/2016', 8.5)
INSERT INTO #temphours
  VALUES (1, '1/4/2016', 8.5)
INSERT INTO #temphours
  VALUES (2, '2/4/2016', 8.5)
INSERT INTO #temphours
  VALUES (3, '3/5/2016', 8.5)
INSERT INTO #temphours
  VALUES (4, '4/6/2016', 8.5)
INSERT INTO #temphours
  VALUES (5, '5/7/2016', 8.5)



-- Construct the column list for the IN clause
SET @dynamicCols = STUFF((SELECT
  N',' + QUOTENAME(w) AS [text()]
FROM (SELECT DISTINCT
  DATEPART(wk, workDate) AS W
FROM #temphours) AS W
ORDER BY W
FOR xml PATH (''))
,
1, 1, N'');


-- Construct the full T-SQL statement
-- and execute dynamically

SET @dynamicSql = N'SELECT *
            FROM (SELECT empId, datepart(wk,workDate) as WeekNo, hoursWorked
                    FROM dbo.#temphours) AS I
            PIVOT(SUM(hoursWorked) FOR WeekNo IN(' + @dynamicCols + N')) AS P;';

EXEC sp_executesql @dynamicSql;

GO

答案 1 :(得分:0)

尝试SUM()这会让你到达那里。

SELECT Color, SUM(ListPrice), SUM(StandardCost)  
    FROM Production.Product  
    WHERE Color IS NOT NULL   
        AND ListPrice != 0.00   
        AND Name LIKE 'Mountain%'  
    GROUP BY Color  
    ORDER BY Color;  
GO  

我相信问题中的更多信息会为您提供更好的答案。