2016-09-16 62 views
-3

如何計算每週員工的總工作時數。如何在Tsql中計算員工周工作時間

employee week1 week2 week3 week4 
rams   50  48  49  54 
+1

是你需要的輸出嗎?如果是這樣,那麼包含原始數據的數據庫模式是什麼? – AdaTheDev

+0

是的。基於員工的工作時間。 @AdaTheDev –

+0

請提供源數據及其表結構。 – iamdave

回答

0

不知道你的表的結構使得它很難,但如果是類似下面這樣:那麼你可以使用透視使用動態SQL:

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 
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 

我相信問題中的更多信息會給你更好的答案。