[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1802
  • Last Modified:

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

0
mgordon-spi
Asked:
mgordon-spi
  • 7
  • 3
  • 2
  • +1
1 Solution
 
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
 
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
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

 
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
 
Mark WillsTopic 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
 
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

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

  • 7
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now