I'm going to post this now anyway - it's the one I was trying to post earlier. Apologies - it contains a lot of what the others have said
e technique you are looking for is JOIN - see this article
Visual Representation of SQL Joins[
^]
There is no need to use CASE and I have no idea why you are trying to CAST something.
From your description of your tables you are making mistakes with your database schema. the ActiveCustomer flag is a feature of a Contact or Customer
not the Transactions for the customer. You need to read up on
Database Normalization[
^]
It's also very confusing because your Table1 already has CustomerID on it so I have no idea why you need to go somewhere to get the "correct" CustomerID.
I used some sample tables that look like this:
create table table1
(
[Account ID] varchar(7),
CustomerID int,
[State] varchar(3)
)
insert into table1 values
('4564640', 252, 'TX'),
('4561210', 257, 'WI'),
('4564620', 253, 'TX'),
('4564720', 259, 'NM')
create table contact
(
[Account ID] varchar(7),
[CustomerID] int,
ActiveCustomer bit,
FirstName varchar(50)
)
insert into contact values
('4564640', 252, 1, 'John'),
('4564620', 253, 0, 'Fred')
create table [transactions]
(
[CustomerID] int,
transdate date
)
insert into transactions values
(252, getdate()),
(252, getdate()),
(253, getdate())
All you need to do is do a join across the table to get the information you need:
lect c.CustomerID, t1.[Account ID], FirstName, [State], CASE WHEN ActiveCustomer = 1 THEN 'Active' ELSE 'Inactive' END AS [status]
from transactions t
inner join contact c on t.CustomerID = c.CustomerID
inner join table1 t1 on t1.[Account ID] = c.[Account ID]
You can include a WHERE clause to omit inactive customers if you want to:
WHERE c.ActiveCustomer = 1
If one or more of the tables is on a different server then you just need to ensure that you use the fully qualified table names
e.g.
MyOtherServer.DatabaseName.schemaname.tablename
You may need to set the servers up as
Linked Servers (Database Engine)[
^]