Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 using group by clause wih multiple tables

Author  Topic 

asthasharma017
Starting Member

2 Posts

Posted - 2012-07-02 : 13:39:56
Hi

I am trying to make a qurey for combining two tables using group by clause

tables are-

table 1-
department

deptid deptname
1 c
2 c++
3 java



employee
empid empsal deptid
1 1000 1
2 2000 2
3 3000 3
4 1000 1
5 2000 2
6 3000 3
7 1000 1
8 2000 2
9 3000 3
10 1000 1



now the query requires to make another table having two columns

deptname totalsal
c 4000
c++ 6000
java 9000


i'v tried a lot but not getting how to make this query. the query i made is

SELECT Department.DeptId,SUM(Employee.EmpSal) as TotalSal
FROM Department, Employee
GROUP BY Department.DeptId

but it is showing wrong result.

please help

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2012-07-02 : 14:09:06
You need to add a join in there.

FROM Table1
JOIN Table2
ON Table1.Column1 = Table2.Column1


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-02 : 19:34:09
and just to clarify what you've done is just relating the tables on any condition which was causing a cartesian product between them and giving you wrong result for total.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

asthasharma017
Starting Member

2 Posts

Posted - 2012-07-02 : 21:39:14
Using JOIN i got the correct query. thanks.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2012-07-03 : 01:07:21


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -