Solved

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

Posted on 2008-10-14
13
1,789 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
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

by Mark Wills Attending one of Rob Farley's seminars the other day, I heard the phrase "The Accidental DBA" and fell in love with it. It got me thinking about the plight of the newcomer to SQL Server...  So if you are the accidental DBA, or, simp…
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

707 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

15 Experts available now in Live!

Get 1:1 Help Now