Solved

Nested Select, Union or Join??? SQL Help!

Posted on 2008-10-14
13
1,793 Views
Last Modified: 2012-05-05
Hi All, I have two SQL Statements that I am really hoping to combine to extract some infromation from out CRM package.

The first statement retreives a list of companies that we have not had contact with in the last 30 days, the second statement retreives a record that shows the last time an Engineer visited that company/client.

I was really hoping that I could nest the statments to combine the output, in other words Retreive the list of companies and have an accompanying colums that show the last person to visit and the date that occured.

I know a Union wont work here as the fields are different.

Any Ideas?


SELECT   c.strCompanyName, c.ID

FROM      tblCompany c

LEFT JOIN  tblTimesheet  a

  ON c.ID = a.intClientID 

 AND a.dtWorkDate >= DATEADD(day, -30, getdate())

WHERE a.intClientID  IS NULL

 

SELECT Top 1 tblCompany.ID, tblCompany.strCompanyName, tblTimeSheet.dtWorkDate,tblDomainAccountMap.strDomainUsername

FROM         tblTimeSheet INNER JOIN

                      tblCompany ON tblTimeSheet.intClientID = tblCompany.ID INNER JOIN

                      tblDomainAccountMap ON tblTimeSheet.intEngineerID = tblDomainAccountMap.intUserID

Where tblCompany.ID=C.ID Order By dtWorkDate Desc

Open in new window

0
Comment
Question by:mgordon-spi
  • 7
  • 3
  • 2
  • +1
13 Comments
 
LVL 17

Expert Comment

by:HuyBD
ID: 22718108
try add more columns to 1st query
(SELECT   c.ID,c.strCompanyName, NULL,NULL

FROM      tblCompany c

LEFT JOIN  tblTimesheet  a

  ON c.ID = a.intClientID 

 AND a.dtWorkDate >= DATEADD(day, -30, getdate())

WHERE a.intClientID  IS NULL)

 UNION ALL

(SELECT Top 1 tblCompany.ID, tblCompany.strCompanyName, tblTimeSheet.dtWorkDate,tblDomainAccountMap.strDomainUsername

FROM         tblTimeSheet INNER JOIN

                      tblCompany ON tblTimeSheet.intClientID = tblCompany.ID INNER JOIN

                      tblDomainAccountMap ON tblTimeSheet.intEngineerID = tblDomainAccountMap.intUserID

Where tblCompany.ID=C.ID Order By dtWorkDate Desc)

Open in new window

0
 

Author Comment

by:mgordon-spi
ID: 22718118
Apart from the error I got (Incorrect syntax near the keyword 'Order'), once I removed the ORDER BY Clause the biggest problem is that the second statement doenst know how to deal with C.ID in the where clause.

CID comes from the first statement.
0
 
LVL 42

Expert Comment

by:dqmq
ID: 22718265
This should be pretty close:
SELECT   c.strCompanyName, c.ID, b.dtWorkDate, d.strDomainUsername

FROM      tblCompany c

LEFT JOIN  tblTimesheet  a

  ON c.ID = a.intClientID 

 AND a.dtWorkDate >= DATEADD(day, -30, getdate())
 

LEFT JOIN tblTimesheet b

  ON c.ID = b.intClientID

LEFT JOIN tblDomainAccountMap d ON b.intEngineerID = d.intUserID
 

WHERE a.intClientID  IS NULL

AND b.dtWorkDate = 

(Select max(e.dtWorkDate) from tblTimesheet e where e.intClientID = b.intClientID)

Open in new window

0
 

Author Comment

by:mgordon-spi
ID: 22719147
ok, so it has definately populated the right fields, but its producing duplicates, so I am getting two or three of the same company appearing. Maybe I have to do this programatically?
0
 
LVL 51

Accepted Solution

by:
Mark Wills earned 500 total points
ID: 22719555
OK the basic selection criteria is found in :


SELECT   c.strCompanyName, c.ID, t.dtworkdate, m.strdomainusername
FROM      tblCompany c
LEFT JOIN  tblTimesheet  t  ON c.ID = t.intClientID
LEFT JOIN  tblDomainAccountMap m ON t.intEngineerID = m.intUserID
WHERE t.dtWorkDate <= getdate() - 30
Order By dtWorkDate Desc

So, all we need to do is to get the "top" row for each c.ID... So, since you are on SQL 2005 or 2008... Can use the row_number function... and could even extend that to a CTE query, but much of a muchnes in this case...


SELECT * from(

SELECT   c.strCompanyName, c.ID, t.dtworkdate, m.strdomainusername,

         ROW_NUMBER() OVER ( partition by c.strcompanyname,c.id ORDER BY isnull(t.dtworkdate,'19000101') DESC) AS RowNumber

FROM      tblCompany c

LEFT JOIN  tblTimesheet t ON c.ID = t.intClientID 

LEFT JOIN  tblDomainAccountMap m ON t.intEngineerID = m.intUserID

WHERE isnull(t.dtWorkDate,'19000101') <= getdate() - 30

) as details where Rownumber = 1

Open in new window

0
 

Author Comment

by:mgordon-spi
ID: 22719626
Excellent Job! This is looking quite close.

I just have a few questions, can you shed some light on "isnull(t.dtWorkDate,'19000101')", I'm getting quite a few NULL's returned in hte dtworkDate Column which is strange becuase every record in tblTimesheet has a value in dtWorkDate.

We are also getting records that have a Null Value in strDomainUsername, this is usually an empty field either.

any Ideas why its choosing to return a null value?
0
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

Author Comment

by:mgordon-spi
ID: 22719656
Apologies, that should read "this is usually NOT an empty field either"
0
 

Author Comment

by:mgordon-spi
ID: 22719697
OK, got to the bottom of the Nulls - Your query is perfect!! Well Done!

Would I be better off using Coalesce() instead of the isNull line? Would this work?

0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 22719703
Understand the occasional typo - no apologies needed - you should see the plethora of typo's I make on any given day...

Reason being that I wanted to include every client with or without timesheets given the 30 day criteria - had a look at your previous posting and kind of indicated that "no timesheets" where also wanted. That might not be the entire reason, but a good portion of it.

Timesheet is left joined to company, so, they do not need to exist... If you want to "pin" that down a bit more, then make it an inner join - ie so that timesheets must exist.
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 22719709
Crossed e-mails...

Coalesc - maybe, in these cases just as easy to use isnull...
0
 

Author Comment

by:mgordon-spi
ID: 22719716
Great - thanks very much for you help 500 smakers coming your way ;)
0
 

Author Closing Comment

by:mgordon-spi
ID: 31506188
Thanks for your help, I can see now I have a few years of SQL ahead of me ;)
0
 
LVL 42

Expert Comment

by:dqmq
ID: 22721334
If I'm not mistaken, you get multiple rows per company back when there was more than one timesheet row on the day of the last visit.  Since you also wanted the "last person to visit", that represents a "tie".   I decided to give you back all the ties.   Perhaps you have a tie breaker column, but there is mention of it in the question.  As it stands, you just pick one at random.

 
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

If you find yourself in this situation “I have used SELECT DISTINCT but I’m getting duplicates” then I'm sorry to say you are using the wrong SQL technique as it only does one thing which is: produces whole rows that are unique. If the results you a…
Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
Concerto provides fully managed cloud services and the expertise to provide an easy and reliable route to the cloud. Our best-in-class solutions help you address the toughest IT challenges, find new efficiencies and deliver the best application expe…

911 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

23 Experts available now in Live!

Get 1:1 Help Now