Shivam Sharma Shivam Sharma - 11 months ago 42
SQL Question

Add values of a column and display added result in new table

The table with the data that I have

In the above table I have the columns : weekNumber , weeklyHours , points_Rewarded.

There are four employees : a,b,c,d

I have the values for week1,week2,week3, and so on ( I can have data for many more weeks also such as week4,week5, etc)

I want to write a query such that after passing the query I get the total of the weeklyHours and points_Rewarded for each employee in a new table.
The kind of table that the query should give me is here the desired table that I want after passing the query

Please help me with the query.

Thanks in advance.

Answer Source

You can use GROUP BY to achieve aggregate values. In your case your are looking for SUM.

Try this

DECLARE @tbl TABLE(EmployeeID INT, EmployeeName VARCHAR(100),WeekNumber VARCHAR(100),WeeklyHours INT,pointsRewarded INT);

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