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

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

mgordon-spiAsked:
Who is Participating?
 
Mark WillsConnect With a Mentor Topic AdvisorCommented:
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
 
HuyBDCommented:
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
 
mgordon-spiAuthor Commented:
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
[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

 
dqmqCommented:
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
 
mgordon-spiAuthor Commented:
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
 
mgordon-spiAuthor Commented:
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
 
mgordon-spiAuthor Commented:
Apologies, that should read "this is usually NOT an empty field either"
0
 
mgordon-spiAuthor Commented:
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
 
Mark WillsTopic AdvisorCommented:
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
 
Mark WillsTopic AdvisorCommented:
Crossed e-mails...

Coalesc - maybe, in these cases just as easy to use isnull...
0
 
mgordon-spiAuthor Commented:
Great - thanks very much for you help 500 smakers coming your way ;)
0
 
mgordon-spiAuthor Commented:
Thanks for your help, I can see now I have a few years of SQL ahead of me ;)
0
 
dqmqCommented:
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
All Courses

From novice to tech pro — start learning today.