2016-09-06 20 views
1

The table with the data that I have在新表

添加列的值,並顯示相加的結果在上表中我有列:weekNumber,weeklyHours,points_Rewarded。

有四種員工:A,B,C,D

我有week1,week2,譯員更加值,依此類推(I可以有更多的周也如week4,week5數據,等)

我想編寫一個查詢,使得經過查詢之後,我得到的總的weeklyHourspoints_Rewarded每個員工在一個新表。 查詢應該給我的表的種類是the desired table that I want after passing the query

請幫我進行查詢。

在此先感謝。

回答

2

您可以使用GROUP BY來實現聚合值。在你的情況下,你正在尋找SUM

試試這個

DECLARE @tbl TABLE(EmployeeID INT, EmployeeName VARCHAR(100),WeekNumber VARCHAR(100),WeeklyHours INT,pointsRewarded INT); 
INSERT INTO @tbl VALUES 
(1,'a','week1',10,20) 
,(2,'b','week1',1,20) 
,(3,'c','week1',20,20) 
,(4,'d','week1',30,30) 
,(1,'a','week2',11,10) 
,(2,'b','week2',44,10) 
,(3,'c','week2',5,10) 
,(4,'d','week2',6,40) 
,(1,'a','week3',7,10) 
,(2,'b','week3',88,10) 
,(3,'c','week3',9,10) 
,(4,'d','week3',0,10); 

SELECT tbl.EmployeeID 
     ,tbl.EmployeeName 
     ,SUM(tbl.WeeklyHours) AS Total_Weekly_Hours 
     ,SUM(pointsRewarded) AS Total_Points 
FROM @tbl AS tbl 
GROUP BY tbl.EmployeeID, tbl.EmployeeName 
+0

感謝lot.forgot說,我有一個EMPLOYEE_ID列too.What如果我想在結果 –

+0

@ShivamSharma插入EMPLOYEE_ID列,看到我更新 – Shnugo

+0

感謝一噸。你節省了很多我的時間.. –

0

與下面的查詢嘗試。

 SELECT EmployeeName 
      ,SUM (weeklyHours)Total_weekly_hours 
      ,SUM (pointsrewarded) TotalPoints 
     FROM YourTable 
    Group By EmployeeName 
0

這是一個簡單的GROUP BY。您希望按名稱對員工進行分組,以便在GROUP BY聲明中指定employeename。然後選擇你想如何分組其他列。在這種情況下,你要SUM他們:

SELECT employeename, 
SUM(weeklyhours) as total_weekly_hours, 
SUM(points_rewarded) as total_points 
GROUP BY employeename 

請注意,您也可以在地方使用AVGMINMAXSUM取決於你想要查找。 AS子句指定要在輸出中調用特定列的內容。

這裏測試:http://sqlfiddle.com/#!9/2a96f

+0

非常感謝... –