I have a customers table t1
which looks like this:
cust_id cust_zip
1000 19999
2000 29999
4000 39999
5000 89999
I have a transactions table t2
that looks like this:
store_id cust_id cust_zip
100 1000 19999
100 2000 29999
100 3000 39999
I'm trying to pull t2.store_id
, t2.cust_zip
and t1.cust_id
into one table where:
cust_zip
field matches cust_id
field does not match The result I'm looking for is:
store_id cust_zip cust_id
100 39999 4000
In this example, cust_id
5000
is not pulled from t1
because the associated cust_zip
89999
is not associated with store_id
100
in t2
. What's the best way to do this?
Have you tried a simple conditional join?
Select t2.store_id,t2.cust_zip,t1.cust_id
from t2
join t1 on t2.cust_zip=t1.cust_zip and t2.cust_id<>t1.cust_id
I do wonder though why your database is not normalized. I would think transaction table would probably have store_zip then you are trying to match store zip with customer zip
Sounds like a JOIN and a WHERE query. Something like this: (query might be different depending on your SQL dialect)
SELECT t2.store_id, t2.cust_zip, t1.cust_id FROM t1
JOIN t2 ON t1.cust_zip = t2.cust_zip
WHERE t1.cust_zip = t2.cust_zip AND
t1.cust_id != t2.cust_id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.