SQL Two Table Joins With Group By

Posted on 2012-03-28
Last Modified: 2012-03-28
I have two tables that contain the same FK reference.  I need to write a query that joins result set from both tables and groups them by the same FK.  For example,

SELECT e.attendedOrientation, sum(DATEDIFF(mm,e.hiredDate,GETDATE()))
FROM employee e
      WHERE e.attendedOrientation IS NOT NULL NULL
GROUP BY e.attendedOrientation

1     100
2     24
3     21


SELECT t.attendedOrientation, sum(DATEDIFF(mm,t.hiredDate,termDate))
FROM term t
      WHERE t.attendedOrientation IS NOT NULL NULL
GROUP BY t.attendedOrientation

1     14
2     NULL
3     6

So what I need when I add result set together should be
1     114
2     24
3     27

but I get
1     708
2     NULL (There are no id 2 in ts table)
3     87

Can anyone help me join results together and get correct results.  This is the last query I attempted

Here is expanded query:
SELECT e.attendedOrientation, sum(DATEDIFF(mm,e.hiredDate,GETDATE()))
        + sum(DATEDIFF(mm,t.hiredDate,terminationDate))
FROM employee e
FULL JOIN termts t ON
      e.attendedOrientation = t.attendedOrientation
      WHERE e.attendedOrientation IS NOT NULL OR t.attendedOrientation IS NOT NULL
GROUP BY e.attendedOrientation
Question by:ICG

Accepted Solution

rajeevnandanmishra earned 500 total points
ID: 37777276
The easiest way is to do Union like below:
SELECT x.attendedOrientation, sum(x.mySum) as mySum from (
SELECT e.attendedOrientation, sum(DATEDIFF(mm,e.hiredDate,GETDATE())) mySum
FROM employee e
      WHERE e.attendedOrientation IS NOT NULL NULL
GROUP BY e.attendedOrientation
SELECT t.attendedOrientation, sum(DATEDIFF(mm,t.hiredDate,termDate))
FROM term t
      WHERE t.attendedOrientation IS NOT NULL NULL
GROUP BY t.attendedOrientation) x
GROUP BY x.attendedOrientation

If you find it running very slow, then we can try some different way also.

Expert Comment

ID: 37777377
Scalar Functions-Horizontal Math:

 3 + 0                                 = 3
 3 + NULL                         = NULL
 3 + Coalesce( NULL, 0 )  = 3

Aggregate Functions-Vertical Math: ( Column functions )

 Sum( NULL, NULL )   = NULL
 Sum( 3, NULL )          = 3

Try removing the WHERE clause and accommodating the NULLs:

SELECT e.attendedOrientation,
       Coalesce( sum( DATEDIFF(mm,e.hiredDate,GETDATE()) ), 0 )
        + Coalesce( sum( DATEDIFF(mm,t.hiredDate,terminationDate) ), 0 )
FROM employee e
FULL JOIN termts t ON
      e.attendedOrientation = t.attendedOrientation
GROUP BY e.attendedOrientation

Open in new window

edit: Check out your vendor implementation, but this is how it works on mine (DB2-iSeries)

Author Closing Comment

ID: 37777644
This solution worked perfectly!    The correct totals were present in the result set.  I was unaware that you could go a second group by after union and a third to combine all the information.  Great solution.  You saved me some headaches.

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

948 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now