Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 t-sql query return all rows from table1

Author  Topic 

tjoppie
Starting Member

4 Posts

Posted - 2010-09-15 : 15:10:07
Hi there,

I've got two tables:

tClient:
ClientID Name
1 John
2 Sally
3 Joe
4 Nick

tInvoice:
InvoiceID ClientID DateAdded
1 1 2010/09/01
2 1 2010/09/02
3 3 2010/09/01

I'm trying to write sproc where I need the following info:

All the invoices for all clients between 2010/09/01 and 2010/09/30, but the catch is, I need all the clients to be in the dataset that get's returned... so for eg my return dataset will look like this:

ClientID InvoiceID DateAdded
1 1 2010/09/01
1 2 2010/09/02
2 NULL NULL
3 3 2010/09/01
4 NULL NULL

Now I've tried something like this:

SELECT tClient.ClientID, tInvoice.InvoiceID, tInvoice.DateAdded
FROM tClient LEFT OUTER JOIN
tInvoice ON tClient.ClientID = tInvoice.ClientID
WHERE (tInvoice.DateAdded BETWEEN CONVERT(DATETIME, '2010-09-01 00:00:00', 102) AND CONVERT(DATETIME, '2010-09-30 00:00:00', 102))

but this returns only return the clients who has invoices for that date range. I need all the clients returned from tClient in my dataset, as shown above. Any idea on how I'll be able to do this?

Thanks alot in advance


tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-09-15 : 15:17:36
You need add your WHERE clause to the LEFT JOIN:

SELECT c.ClientID, i.InvoiceID, i.DateAdded
FROM tClient c
LEFT JOIN tInvoice i
ON c.ClientID = i.ClientID
AND i.DateAdded BETWEEN '09/01/2010' AND '09/30/2010'

See this for more information: http://www.sqlteam.com/article/additional-criteria-in-the-join-clause

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -