Click here to Skip to main content

SQL Group by With Joins

How to use Group By clause when joining to table Let's consider one scenario where I have two table employees (contains employee detail) and sales (contains infomation about sales done by employee).Structure of...
Sign Up to vote bad good
Add a reason or comment to your vote: x
Votes of 3 or less require a comment
How to use Group By clause when joining to table
 
Let's consider one scenario where I have two table employees (contains employee detail) and sales (contains infomation about sales done by employee).
 
Structure of Employee:
EmployeeID
EmployeeFirstName
EmployeeLastName
EmployeeEmailID
EmployeeContactNo
 
Structure of Sales:
SalesID
SalesEmployeeID
SalesDate
SalesTotal
 
Now I want to get total sales done by employee with employee name. For that, I write a query like:
 
Select EmployeeFirstName,EmployeeLastName,sum(SalesTotal)
from Employee  
inner join Sales on EmployeeID= SalesEmployeeID
group by EmployeeFirstName,EmployeeLastName,SalesTotal
 
But there is one problem in the above Query. I have to add two more extra fields in group by clause which make query inefficient and make no sense logically

So the solution for this is to use derive table which makes sense logically and clears query

Select EmployeeID,EmployeeFirstName,EmployeeLastName,TotalSales
from Employee  
inner join 
 (Select SalesEmployeeID,sum(SalesTotal) as TotalSales
    from  Sales group by SalesEmployeeID) empSales 
on empSales.SalesEmployeeID= EmployeeID
Posted 8 Feb '10
Edited 15 Feb '10


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Your Filters
Interested
Ignored
     
  1. SAKryukov (1,105)
  2. OriginalGriff (1,090)
  3. Abhinav S (475)
  4. thatraja (455)
  1. SAKryukov (9,074)
  2. Christian Graus (5,846)
  3. OriginalGriff (4,523)
  4. Abhinav S (4,310)
  5. thatraja (4,230)

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --

Advertise | Privacy | Mobile
Web02 | 2.5.120210.1 | Last Updated 22 Nov 2011
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid