添加列的值并在新表中显示添加的结果

时间:2016-09-06 19:19:28

标签: sql sql-server tsql sql-server-2005 sql-server-2012

The table with the data that I have

在上表中我有列:weekNumber,weeklyHours,points_Rewarded。

有四名员工:a,b,c,d

我有第1周,第2周,第3周等的值(我可以有更多周的数据,例如第4周,第5周等)

我想写一个查询,以便在通过查询后,我得到每个员工的 weeklyHours points_Rewarded 的总和新表。 查询应该向我提供的表格类型为the desired table that I want after passing the query

请帮我查询。

提前致谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

尝试使用以下查询。

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

答案 2 :(得分:0)

这是一个简单的GROUP BY。您希望按名称对员工进行分组,因此请在GROUP BY语句中指定employeename。然后,只需选择您希望如何对其他列进行分组。在这种情况下,您需要SUM他们:

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

请注意,您也可以使用AVGMINMAX代替SUM,具体取决于您要查找的内容。 AS子句指定要在输出中调用特定列的内容。

在这里测试:http://sqlfiddle.com/#!9/2a96f