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 2000 Forums
 Transact-SQL (2000)
 selecting all records in 1st table,some in second

Author  Topic 

adiel
Starting Member

16 Posts

Posted - 2008-05-12 : 15:26:04
This must be a simple one but cannot figure it out right now:

-I want to select all the records from table 1 that match the WHERE clause.
-I want to select all the records from table 2 that match the WHERE clause. The records from table 2 are less than the records from table 1. (not all customers will have a customercode of FEE20C)

Here is the current select statement:


select *
from table1 t1(nolock)
left outer join
table2 t2(nolock)
on t1.customer = t2.customer
where t1.customercode in ('FEE20') and -all customers
t2.customercode in ('FEE20C') -only some have FEE20C



The select should select ALL the customers from table1. But, its only selecting the ones that have both FEE20 and FEE20C. I know this should be a simple query. What I would like it is to return all the customers and if the customer does not have a FEE20C record in table2, return null for those fields.

Thanks Before Hand,
Adiel

adiel
Starting Member

16 Posts

Posted - 2008-05-12 : 16:08:51
Ok guys, I think I got it, let me know if you see something wrong with the statement:

select *
from table1 t1(nolock)
left outer join
table2 t2(nolock)
on t1.customer = t2.customer and
t1.customercode in ('FEE20') and
t2.customercode in (NULL, 'FEE20C')
where t1.customercode in ('FEE20')
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-05-12 : 16:22:29
Your solution seems unnecessary. In your first post, you say you want to return all customers from table1, yet you are filtering table1 with 'FEE20'. So which is it? ALL or FEE20?

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

Database maintenance routines:
http://weblogs.sqlteam.com/tarad/archive/2004/07/02/1705.aspx
Go to Top of Page

adiel
Starting Member

16 Posts

Posted - 2008-05-12 : 16:51:05
>>Your solution seems unnecessary. In your first post, you say you want to return all customers from table1, yet you are filtering table1 with 'FEE20'. So which is it? ALL or FEE20?

Sorry, I meant to say "All customers from table1 that have FEE20". The second query I wrote above works, I just want to make sure it is correct...
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-05-13 : 00:33:42
[code]select *
from table1 t1(nolock)
left outer join
table2 t2(nolock)
on t1.customer = t2.customer and
t1.customercode in ('FEE20') and
(t2.customercode IS NULL OR t2.customercode='FEE20C')
where t1.customercode in ('FEE20')[/code]
Go to Top of Page
   

- Advertisement -