Select with Sub Query - sql

I have two selects in my procedure, but I want to select just the rows that the IDENTIFICACAO_A from the first Select are in common with the IDENTIFICACAO_B from the second Select.
Query:
SELECT
(CONVERT(VARCHAR,fic.reg_codigo_lotado_atual) + '.' + CONVERT(VARCHAR,fic.cla_codigo) + '.' + CONVERT(VARCHAR,fic.reg_codigo_lotado_origem) + '.' + CONVERT(VARCHAR,fic.fic_numero_livro) + '/' + CONVERT(VARCHAR,fic.fic_versao)) AS IDENTIFICACAO_A,
cla.cla_nome,
fic.fic_ca,
fic.fic_fa,
fic.reg_codigo_lotado_atual,
fic.cla_codigo,
fic.reg_codigo_lotado_origem,
fic.fic_numero_livro,
fic.fic_versao,
fic.fic_ato_oficial,
fic_localizacao_numero,
fic_localizacao_data_em,
qua.qua_nome,
fic.fic_localizacao_do,
adm.adm_codigo_ua,
adm.adm_codigo_uv,
adm.adm_digito,
adm.adm_decodificada,
adm.adm_sigla,
form.for_nome,
fic.fic_ocupacao_data,
fic.fic_ocupacao_do,
fic.fic_ocupacao_data_cessacao,
fic.fic_ocupacao_do_cessacao,
ser.ser_nome,
ser.ser_rg,
ser.ser_cpf,
fic.fic_ocupacao_observacao,
esp.esp_descricao,
fic.fic_alteracao_vigencia,
fic.fic_alteracao_decreto,
fic.fic_alteracao_data,
fic.fic_alteracao_qua_codigo,
fic.fic_alteracao_do,
fic.fic_situacao_vc,
fic.fic_situacao_pp,
fic.fic_situacao_ocupado,
fic.fic_nova_identificacao,
fic.fic_observacoes_gerais
FROM
SICAF.dbo.tab_fichas AS fic
INNER JOIN
SICAF.dbo.tab_classes AS cla ON cla.cla_codigo = fic.cla_codigo
LEFT JOIN
SICAF.dbo.tab_sub_quadros AS qua ON qua.qua_codigo = fic.qua_codigo
LEFT JOIN
SICAF.dbo.tab_unidade_adm AS adm ON adm.adm_codigo = fic.adm_codigo
LEFT JOIN
SICAF.dbo.tab_formas AS form ON form.for_codigo = fic.for_codigo
LEFT JOIN
SICAF.dbo.tab_servidores AS ser ON ser.ser_codigo = fic.ser_codigo
LEFT JOIN
SICAF.dbo.tab_especies AS esp ON esp.esp_codigo = fic.esp_codigo
SELECT
(CONVERT(VARCHAR,fic.reg_codigo_lotado_atual) + '.' + CONVERT(VARCHAR,fic.cla_codigo) + '.' + CONVERT(VARCHAR,fic.reg_codigo_lotado_origem) + '.' + CONVERT(VARCHAR,fic.fic_numero_livro) + '/' + CONVERT(VARCHAR,fic.fic_versao)) AS IDENTIFICACAO_B,
cla.cla_nome,
fic.fic_ca,
fic.fic_fa,
fic.reg_codigo_lotado_atual,
fic.cla_codigo,
fic.reg_codigo_lotado_origem,
fic.fic_numero_livro,
fic.fic_versao,
fic.fic_ato_oficial,
fic_localizacao_numero,
fic_localizacao_data_em,
qua.qua_nome,
fic.fic_localizacao_do,
adm.adm_codigo_ua,
adm.adm_codigo_uv,
adm.adm_digito,
adm.adm_decodificada,
adm.adm_sigla,
form.for_nome,
fic.fic_ocupacao_data,
fic.fic_ocupacao_do,
fic.fic_ocupacao_data_cessacao,
fic.fic_ocupacao_do_cessacao,
ser.ser_nome,
ser.ser_rg,
ser.ser_cpf,
fic.fic_ocupacao_observacao,
esp.esp_descricao,
fic.fic_alteracao_vigencia,
fic.fic_alteracao_decreto,
fic.fic_alteracao_data,
fic.fic_alteracao_qua_codigo,
fic.fic_alteracao_do,
fic.fic_situacao_vc,
fic.fic_situacao_pp,
fic.fic_situacao_ocupado,
fic.fic_nova_identificacao,
fic.fic_observacoes_gerais
FROM
SICAF2.dbo.tab_fichas AS fic
INNER JOIN
SICAF2.dbo.tab_classes AS cla ON cla.cla_codigo = fic.cla_codigo
LEFT JOIN
SICAF2.dbo.tab_sub_quadros AS qua ON qua.qua_codigo = fic.qua_codigo
LEFT JOIN
SICAF2.dbo.tab_unidade_adm AS adm ON adm.adm_codigo = fic.adm_codigo
LEFT JOIN
SICAF2.dbo.tab_formas AS form ON form.for_codigo = fic.for_codigo
LEFT JOIN
SICAF2.dbo.tab_servidores AS ser ON ser.ser_codigo = fic.ser_codigo
LEFT JOIN
SICAF2.dbo.tab_especies AS esp ON esp.esp_codigo = fic.esp_codigo
What can I do to return both Selects?

You can use inner join between both queries:
Select * From
(
SELECT
(CONVERT(VARCHAR,fic.reg_codigo_lotado_atual) + '.' + CONVERT(VARCHAR,fic.cla_codigo) + '.' + CONVERT(VARCHAR,fic.reg_codigo_lotado_origem) + '.' + CONVERT(VARCHAR,fic.fic_numero_livro) + '/' + CONVERT(VARCHAR,fic.fic_versao)) AS IDENTIFICACAO_A,
cla.cla_nome,
fic.fic_ca,
fic.fic_fa,
fic.reg_codigo_lotado_atual,
fic.cla_codigo,
fic.reg_codigo_lotado_origem,
fic.fic_numero_livro,
fic.fic_versao,
fic.fic_ato_oficial,
fic_localizacao_numero,
fic_localizacao_data_em,
qua.qua_nome,
fic.fic_localizacao_do,
adm.adm_codigo_ua,
adm.adm_codigo_uv,
adm.adm_digito,
adm.adm_decodificada,
adm.adm_sigla,
form.for_nome,
fic.fic_ocupacao_data,
fic.fic_ocupacao_do,
fic.fic_ocupacao_data_cessacao,
fic.fic_ocupacao_do_cessacao,
ser.ser_nome,
ser.ser_rg,
ser.ser_cpf,
fic.fic_ocupacao_observacao,
esp.esp_descricao,
fic.fic_alteracao_vigencia,
fic.fic_alteracao_decreto,
fic.fic_alteracao_data,
fic.fic_alteracao_qua_codigo,
fic.fic_alteracao_do,
fic.fic_situacao_vc,
fic.fic_situacao_pp,
fic.fic_situacao_ocupado,
fic.fic_nova_identificacao,
fic.fic_observacoes_gerais
FROM
SICAF.dbo.tab_fichas AS fic
INNER JOIN
SICAF.dbo.tab_classes AS cla ON cla.cla_codigo = fic.cla_codigo
LEFT JOIN
SICAF.dbo.tab_sub_quadros AS qua ON qua.qua_codigo = fic.qua_codigo
LEFT JOIN
SICAF.dbo.tab_unidade_adm AS adm ON adm.adm_codigo = fic.adm_codigo
LEFT JOIN
SICAF.dbo.tab_formas AS form ON form.for_codigo = fic.for_codigo
LEFT JOIN
SICAF.dbo.tab_servidores AS ser ON ser.ser_codigo = fic.ser_codigo
LEFT JOIN
SICAF.dbo.tab_especies AS esp ON esp.esp_codigo = fic.esp_codigo
)tbl1
Inner Join
(
SELECT
(CONVERT(VARCHAR,fic.reg_codigo_lotado_atual) + '.' + CONVERT(VARCHAR,fic.cla_codigo) + '.' + CONVERT(VARCHAR,fic.reg_codigo_lotado_origem) + '.' + CONVERT(VARCHAR,fic.fic_numero_livro) + '/' + CONVERT(VARCHAR,fic.fic_versao)) AS IDENTIFICACAO_B,
cla.cla_nome,
fic.fic_ca,
fic.fic_fa,
fic.reg_codigo_lotado_atual,
fic.cla_codigo,
fic.reg_codigo_lotado_origem,
fic.fic_numero_livro,
fic.fic_versao,
fic.fic_ato_oficial,
fic_localizacao_numero,
fic_localizacao_data_em,
qua.qua_nome,
fic.fic_localizacao_do,
adm.adm_codigo_ua,
adm.adm_codigo_uv,
adm.adm_digito,
adm.adm_decodificada,
adm.adm_sigla,
form.for_nome,
fic.fic_ocupacao_data,
fic.fic_ocupacao_do,
fic.fic_ocupacao_data_cessacao,
fic.fic_ocupacao_do_cessacao,
ser.ser_nome,
ser.ser_rg,
ser.ser_cpf,
fic.fic_ocupacao_observacao,
esp.esp_descricao,
fic.fic_alteracao_vigencia,
fic.fic_alteracao_decreto,
fic.fic_alteracao_data,
fic.fic_alteracao_qua_codigo,
fic.fic_alteracao_do,
fic.fic_situacao_vc,
fic.fic_situacao_pp,
fic.fic_situacao_ocupado,
fic.fic_nova_identificacao,
fic.fic_observacoes_gerais
FROM
SICAF2.dbo.tab_fichas AS fic
INNER JOIN
SICAF2.dbo.tab_classes AS cla ON cla.cla_codigo = fic.cla_codigo
LEFT JOIN
SICAF2.dbo.tab_sub_quadros AS qua ON qua.qua_codigo = fic.qua_codigo
LEFT JOIN
SICAF2.dbo.tab_unidade_adm AS adm ON adm.adm_codigo = fic.adm_codigo
LEFT JOIN
SICAF2.dbo.tab_formas AS form ON form.for_codigo = fic.for_codigo
LEFT JOIN
SICAF2.dbo.tab_servidores AS ser ON ser.ser_codigo = fic.ser_codigo
LEFT JOIN
SICAF2.dbo.tab_especies AS esp ON esp.esp_codigo = fic.esp_codigo
)tbl2
On tbl1.IDENTIFICACAO_A=tbl2.IDENTIFICACAO_B

You can use :
select your_fields from table1
intersect
select your_fields from table2

Use union.
Rename the key column to be the same on both queries, and i would also recommend to save both queries as a temp tables.
So let's say you have your first query stored in temp table q1 and second query in q2 and the key column on both is id.
select from q1 where q1.id in (select id from q2)
union
select from q2 where q2.id in (select id from q1)
Hope I was clear.

You could use IN here. T1 is group of joined tables from first query and T2 is group of joined tables from second query. Syntax is as below.
Select col1,col2,...
From T1
Where IDENTIFICACAO_A in (
Select IDENTIFICACAO_B
From T2
)
You can replace IDENTIFICACAO_A and IDENTIFICACAO_B column names with their concatenated results
If T1 and T2 (described above) are same then;
SELECT X AS IDENTIFICACAO_A,
cla.cla_nome,
fic.fic_ca,...
FROM T1
WHERE X = Y
You can replace X and Y with their string concatenating functions.

Related

SQL JOIN IF EXISTS

I have a query using a JOIN to get some datas in others databases. But in a specific case, my entry will not have any data do do join.
So, it wont return nothing at all.
How can I ignore the join statement if not exists any compatible data?
Here is my SQL query:
SELECT
a.Id,
a.NomeCompleto,
a.CPF,
a.RelacaoFuncional,
a.Estabelecimento,
UPPER(LEFT(a.Cargo, 1)) + LOWER(SUBSTRING(a.Cargo, 2, LEN(a.Cargo))) as Cargo,
b.Unidade,
c.Departamento,
d.CentroCusto + ' - ' + Desc_CCUsto as CentroCusto,
a.UsuarioEspelho,
a.Observacao,
a.UsuarioRequerente,
a.Status,
CONVERT(NVARCHAR(10), a.Data, 103) AS Data,
a.AprovacaoInfra,
a.AprovacaoSistemas,
a.Usuario,
a.TipoSolicitacao
FROM
[SGW].[dbo].[TI01A] a
JOIN
[SGW].[dbo].[Unidade] b ON a.Id_Unidade = b.UnidadeID
JOIN
[SGW].[dbo].[Departamento] c ON a.Id_Departamento = c.DeptoID
JOIN
[HAZTEC_ORC].[dbo].[DimCentroCusto] d ON a.CentroCusto = d.CentroCusto
WHERE
a.Id = 6
You need to use
LEFT JOIN
Your query should be like below
SELECT a.Id,
a.NomeCompleto,
a.CPF,
a.RelacaoFuncional,
a.Estabelecimento,
UPPER(LEFT(a.Cargo, 1)) + LOWER(SUBSTRING(a.Cargo, 2, LEN(a.Cargo))) as Cargo,
b.Unidade,
c.Departamento,
d.CentroCusto + ' - ' + Desc_CCUsto as CentroCusto,
a.UsuarioEspelho,
a.Observacao,
a.UsuarioRequerente,
a.Status,
convert(nvarchar(10), a.Data, 103) as Data,
a.AprovacaoInfra,
a.AprovacaoSistemas,
a.Usuario,
a.TipoSolicitacao
FROM[SGW].[dbo].[TI01A] a
LEFT JOIN[SGW].[dbo].[Unidade] b on a.Id_Unidade = b.UnidadeID
LEFT JOIN[SGW].[dbo].[Departamento] c on a.Id_Departamento = c.DeptoID
LEFT JOIN[HAZTEC_ORC].[dbo].[DimCentroCusto] d on a.CentroCusto = d.CentroCusto
WHERE A.Id = 6

SQL Server 2012 : Multiple Queries in One Stored Procedure

How do I create Stored Procedure on these queries and he output should show which check the anomaly was captured from, along with all the relevant data.
SELECT cm.Cust_id, cm.cust_ref_id4, cm.cust_ref_id3, cm.plan_group, cm.Company_name, cm.Cust_firstname, cm.Cust_lastname
COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID, c3.CompanyName FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID AND cm.cust_ref_id3 = c.pkCustomerID AND cm.cust_ref_id3 >= 1000000 AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN ('A','P','R','G') AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL ORDER BY cust_ref_id4;
and
SELECT [pkCustomerID],b.[pkContractID],[pkCustomerTypeID],[CustomerType],b.[ContractType] AS Contractype1,c.[ContractType]
AS Contractype2 FROM [CORE].[dbo].[Customers] a
JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (SELECT [pkContractID],[ContractType],[fkCustomerID] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE [ContractType] NOT LIKE 'Holdover%')b ON a.pkCustomerID=b.fkCustomerID
LEFT JOIN (SELECT [pkContractID],[fkCustomerID],[ContractType] FROM [CORE].[dbo].[Contracts]
JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID] WHERE ContractType LIKE 'Holdover%')c ON b.fkCustomerID=c.fkCustomerID WHERE [CustomerType] IN ('Customer','Former Customer') AND (b.ContractType IS NULL OR c.ContractType IS NULL)
You question is lacking a very important piece of information, the explanation of what you are trying to do. I took a shot in the dark here as a guess to what you might be looking for. BTW, I ran this through a formatter so it was legible.
SELECT 'Found in query1'
,cm.Cust_id
,cm.cust_ref_id4
,cm.cust_ref_id3
,cm.plan_group
,cm.Company_name
,cm.Cust_firstname
,cm.Cust_lastname
,COALESCE(c.pkCustomerID, c2.fkCustomerID, c3.pkCustomerID, c4.pkCustomerID) AS pkCustomerID
,c3.CompanyName
FROM PRODUCTIONSQL.[SigmaPaTri].[dbo].[CUSTOMER_MASTER] cm
LEFT JOIN PHOENIX.CORE.dbo.Customers AS c ON cust_ref_id4 = c.pkCustomerID
AND cm.cust_ref_id3 = c.pkCustomerID
AND cm.cust_ref_id3 >= 1000000
AND cm.Cust_firstname + ' ' + cm.Cust_lastname = c.CompanyName
LEFT JOIN PHOENIX.CORE.dbo.Contracts AS c2 ON cm.cust_ref_id3 = c2.ConfirmationNumber
WHERE cm.cust_status IN (
'A'
,'P'
,'R'
,'G'
)
AND COALESCE(c.pkCustomerID, c2.fkCustomerID) IS NULL
SELECT 'Found in query 2'
,[pkCustomerID]
,b.[pkContractID]
,[pkCustomerTypeID]
,[CustomerType]
,b.[ContractType] AS Contractype1
,c.[ContractType] AS Contractype2
FROM [CORE].[dbo].[Customers] a
INNER JOIN [CORE].[dbo].[CustomerTypes] ON [pkCustomerTypeID] = [fkCustomerTypeID]
LEFT JOIN (
SELECT [pkContractID]
,[ContractType]
,[fkCustomerID]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE [ContractType] NOT LIKE 'Holdover%'
) b ON a.pkCustomerID = b.fkCustomerID
LEFT JOIN (
SELECT [pkContractID]
,[fkCustomerID]
,[ContractType]
FROM [CORE].[dbo].[Contracts]
INNER JOIN [CORE].[dbo].[ContractTypes] ON [fkContractTypeID] = [pkContractTypeID]
WHERE ContractType LIKE 'Holdover%'
) c ON b.fkCustomerID = c.fkCustomerID
WHERE [CustomerType] IN (
'Customer'
,'Former Customer'
)
AND (
b.ContractType IS NULL
OR c.ContractType IS NULL
)

inner join with multiple records

i have 2 tables TblMemberDetails,TblMemberDetailsSub am using following sql queries to fetch records
QUERY 1
SELECT (TblMemberDetails.MemFname +' '+TblMemberDetails.MemMname +' '+
TblMemberDetails.MemLname)As Name,
TblStateMaster.StateName,
TblDistMaster.DistName,
TblTaluqaMaster.TaluqaName
FROM TblMemberDetails INNER JOIN TblStateMaster
ON TblMemberDetails.StateId = TblStateMaster.StateId
INNER JOIN TblDistMaster ON TblMemberDetails.DistId = TblDistMaster.DistId
INNER JOIN TblTaluqaMaster ON TblMemberDetails.TaluqaId = TblTaluqaMaster.TaluqaId
INNER JOIN TblMemberDetailsSub ON TblMemberDetails.MemId = TblMemberDetailsSub.MemId
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
GROUP BY TblMemberDetailsSub.MemId, TblMemberDetails.MemId,
TblMemberDetails.MemFname, TblMemberDetails.MemMname,
TblMemberDetails.MemLname, TblStateMaster.StateName,
TblDistMaster.DistName, TblTaluqaMaster.TaluqaName
order by TblMemberDetailsSub.MemId Asc
QUERY 2
SELECT TblMemberDetailsSub.MemId, ISNULL(sum(TblMemberDetailsSub.Amount),0) AS TotalAmount,
TblMemberDetailsSub.PayRound, TblMemberDetailsSub.PlanName
FROM TblMemberDetailsSub
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
GROUP BY TblMemberDetailsSub.MemId, TblMemberDetailsSub.PayRound,
TblMemberDetailsSub.PlanName, TblMemberDetailsSub.Amount
ORDER BY TblMemberDetailsSub.MemId Asc
I just want both table result in single set (i user union but it is not working)
how can i merge both queries for single result
Group by in first query is not significant if you have only one row for each memberId in
TblStateMaster ,TblDistMaster ,TblTaluqaMaster also you are not selecting any value from TblMemberDetailsSub in first query . One way to merge the two queries is as follows:
SELECT (TblMemberDetails.MemFname +
' '+
TblMemberDetails.MemMname +
' '+
TblMemberDetails.MemLname)As Name,
TblStateMaster.StateName,
TblDistMaster.DistName,
TblTaluqaMaster.TaluqaName,
T.MemId,
T.TotalAmount,
T.PayRound,
T.PlanName
FROM
TblMemberDetails
INNER JOIN TblStateMaster ON TblMemberDetails.StateId = TblStateMaster.StateId
INNER JOIN TblDistMaster ON TblMemberDetails.DistId = TblDistMaster.DistId
INNER JOIN TblTaluqaMaster ON TblMemberDetails.TaluqaId = TblTaluqaMaster.TaluqaId
Inner join (
select TblMemberDetailsSub.MemId,
ISNULL(sum(TblMemberDetailsSub.Amount),0)As TotalAmount,
TblMemberDetailsSub.PayRound,
TblMemberDetailsSub.PlanName
from TblMemberDetailsSub
WHERE (TblMemberDetailsSub.MemMode = 'Provider')
AND (TblMemberDetailsSub.CycleStatus = 'Uncompleted')
group by TblMemberDetailsSub.MemId,TblMemberDetailsSub.PayRound,TblMemberDetailsSub.PlanName,TblMemberDetailsSub.Amount
) T ON TblMemberDetails.MemId = T.MemId
order by T.MemId Asc

Syntax Error in CASE STATEMENT

Here is my select statement. What I'm trying to do is if an account has more than one ID, I want the phone number to be NULL, ELSE I want the phone number to = phone_number_formatted:
SELECT
v_returned_inventory.order_id,
v_live_inventory.inet_event_description,
v_live_inventory.event_time,
v_cust_phone.phone_number_formatted,
v_live_inventory.event_date,
v_returned_inventory.section_name,
v_returned_inventory.add_usr,
v_live_inventory.num_seats,
v_returned_inventory.acct_id,
v_live_inventory.class_name,
AT_trans_for_emailTrigger.email_addr,
AT_trans_for_emailTrigger.cust_name_id,
premclub.name_first + ' ' + premclub.name_last AS name
FROM
v_returned_inventory
INNER JOIN
v_live_inventory
ON
LEFT(v_returned_inventory.event_name, 6) = LEFT(v_live_inventory.event_name, 6)
AND v_returned_inventory.orderNumber = v_live_inventory.other_info_1 INNER JOIN
AT_trans_for_emailTrigger
ON v_returned_inventory.order_id = AT_trans_for_emailTrigger.order_id
LEFT OUTER JOIN
v_cust_phone
on v_cust_phone.acct_id = v_returned_inventory.acct_id
LEFT OUTER JOIN
OPENQUERY(premclub, 'select name_first, name_last, cust_name_id from dba.v_cust_name') AS premclub
ON AT_trans_for_emailTrigger.cust_name_id = premclub.cust_name_id,
**CASE
WHEN (select
count(cust_name_id)
from
v_cust_phone) > 1 then null
else v_cust_phone.phone_number_formatted
END**
You have the CASE statement in the wrong place, it needs to be in the SELECT. Based on what you currently have, it appears that you might be able to do something like this:
SELECT v_returned_inventory.order_id,
v_live_inventory.inet_event_description,
v_live_inventory.event_time,
case when phone.cnt > 1 then null else v_cust_phone.phone_number_formatted end phone_number_formatted,
v_live_inventory.event_date,
v_returned_inventory.section_name,
v_returned_inventory.add_usr,
v_live_inventory.num_seats,
v_returned_inventory.acct_id,
v_live_inventory.class_name,
AT_trans_for_emailTrigger.email_addr,
AT_trans_for_emailTrigger.cust_name_id,
premclub.name_first + ' ' + premclub.name_last AS name
FROM v_returned_inventory
INNER JOIN v_live_inventory
ON LEFT(v_returned_inventory.event_name, 6) = LEFT(v_live_inventory.event_name, 6)
AND v_returned_inventory.orderNumber = v_live_inventory.other_info_1
INNER JOIN AT_trans_for_emailTrigger
ON v_returned_inventory.order_id = AT_trans_for_emailTrigger.order_id
LEFT OUTER JOIN v_cust_phone
on v_cust_phone.acct_id = v_returned_inventory.acct_id
LEFT OUTER JOIN
(
select count(cust_name_id) cnt, cust_name_id
from v_cust_phone
group by cust_name_id
) phone
on v_cust_phone.cust_name_id = phone.cust_name_id
LEFT OUTER JOIN OPENQUERY(premclub, 'select name_first, name_last, cust_name_id from dba.v_cust_name') AS premclub
ON AT_trans_for_emailTrigger.cust_name_id = premclub.cust_name_id

another union all selecting all the rows that have not already been selected

Right now i have 2 select statements that are joined by a union what i was hopping to do was maybe name the first query like query1 and the second one query2 and then in my third query do a where bookno not in query1 or query2.
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq, 'yes'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 3)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and (t0.both = t1.both)
union all
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq,'YES'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 1)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and t1.seq = t0.seq and (t0.both = t1.both)
order by bookno
END
How about using WITH? You can declare you queries, join them with UNION and them search for the ones not there.
Take a look here: Multiple Select Statements using SQL Server 2005 "WITH" Statement . It should help you get started.
By using WITH statement, you will isolate logic of your queries, making your overall query more understandable.
just wrap your logic around what you wrote:
select bookno
where key not in (
your big select statement...
)