I need to write a simple query as a part of larger function to join two tables. The tables are as under
Table1
Code Subactivity
647 1
647 2
648 3
648 4
Table 2
Subactivity Hours
1 5
2 10
3 7
4 3
The final output should look like
Code hours
647 15
648 10
I have done this before, but today I just cant get my head around it..
DECLARE @t1 TABLE([Code] INT,[Subactivity] INT)
INSERT INTO @t1 VALUES(647,1),(647,2),(648,3),(648,4)
DECLARE @t2 TABLE([Subactivity] INT, [Hours] INT)
INSERT INTO @t2 VALUES(1,5),(2,10),(3,7),(4,3)
SELECT t1.Code,SUM(t2.Hours) hours
FROM @t1 t1 JOIN @t2 t2 ON t1.subactivity = t2.subactivity
GROUP BY t1.CODE
Result
Code hours
647 15
648 10
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.