Help | Site Map
Connecting Tech Pros Worldwide
Reply
 
LinkBack Thread Tools
  #1  
Old October 4th, 2008, 04:33 PM
Newbie
 
Join Date: Oct 2008
Posts: 1
Default Multiple Sum and Join

I have two tables i would like to join to show bonus earned this month and total this year.
First table: empl.

emplID | Name
1 | Bob
2 | James


Second table: Bonus.

empl_id | month | Bonus
1 | 1 | 1000
2 | 1 | 750
1 | 2 | 500
2 | 2 | 1000
1 | 3 | 250
2 | 3 | 500


The output im looking for is (bonus month 3):
Name | Bonus this month | Bonus total
Bob | 250 | 1750
James | 500 | 2250


This is the closest i have got and it fails. So if anyone can point me in the right direction i would be very thankful.
Failing query:

Expand|Select|Wrap|Line Numbers
  1. select e.name, sum(b.bonus) as total,  sum(b1.bonus) as thismth from (empl as e INNER JOIN bonus as b on e.emplID=b.empl_id) INNER JOIN bonus as b1 on e.emplID=b1.empl_id group by e.name
Reply
  #2  
Old October 6th, 2008, 07:42 AM
deepuv04's Avatar
Expert
 
Join Date: Nov 2007
Age: 25
Posts: 202
Default

Hi,
Try the following query.

Expand|Select|Wrap|Line Numbers
  1.  
  2. CREATE TABLE EMPL
  3. (  emplID INT,
  4.    Name VARCHAR(20)
  5. )
  6.  
  7. INSERT INTO EMPL
  8. select 1 , 'Bob' UNION
  9. SELECT 2 , 'James'
  10.  
  11.  
  12. CREATE TABLE Bonus (
  13. empl_id int, month int, Bonus int)
  14.  
  15. INSERT INTO Bonus (
  16. empl_id , month , Bonus)
  17. SELECT 1 , 1 , 1000 UNION
  18. SELECT 2 , 1 , 750 UNION
  19. SELECT 1 , 2 , 500 UNION
  20. SELECT 2 , 2 , 1000 UNION
  21. SELECT 1 , 3 , 250 UNION
  22. SELECT 2 , 3 , 500
  23.  
  24.  
  25. SELECT b.Empl_id,Name,Max(B.month),
  26.         (SELECT Bonus FROM Bonus WHERE Empl_id = B.Empl_id AND [month] = MAX(B.month)) as 'Bonus this month',
  27.         sum(B.bonus) as 'Bonus Earned'
  28. FROM   EMPL INNER JOIN
  29.        Bonus B ON EMPL.emplID = B.Empl_id
  30. GROUP BY B.Empl_id,Name
  31.  
  32.  
  33.  
Thanks
Reply
Reply

Bookmarks

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles