Solved

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

Posted on 2008-10-14
13
1,797 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
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: 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
 

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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

717 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