Union all not displaying all queries - sql

I'm making a query with multiple UNION ALL statements and it's not showing all the results it should show. The SELECT statements all have the same amount of columns, the same aliases and same data types (I've already tried to use CAST, just to be sure). There's only a single SELECT statement that's using a CASE in two different columns and that is all that's different from the others. I've tried to derive that to a sub-select, but to no avail. If I run them by themselves they work fine, matter of fact. If I remove this SELECT statement that has those two CASE's and leave all the rest, it runs fine. There's a lot of unions, so I'll just post the problematic SELECT and one of the other UNION's, since they're all pretty much the same.
All I'm doing in these is pulling values from different events, like employee's taxes, employee's salaries and different adjustments, just to give a clearer view of what I'm doing. I can't provide the real data due to legal reasons. What 's making it not run along the other SELECTs?
Here's the one that's giving me issues
SELECT
CASE
WHEN TCL.CONTADEB IS NOT NULL THEN TCL.CONTADEB
WHEN TCL.CONTACRED IS NOT NULL THEN TCL.CONTACRED
END AS CONTA_CTB
, CASE
WHEN TCL.CONTADEB IS NOT NULL THEN CR.VALOREVENTO
END AS DEBITO
, CASE
WHEN TCL.CONTACRED IS NOT NULL THEN CR.VALOREVENTO
END AS CREDITO
, FP.NOMEFUNC AS FUNCIONARIO
, EV.DESCREVENTO || ' - ' || EXTRACT(MONTH FROM PC.COMPET) || '/' || EXTRACT(YEAR FROM PC.COMPET) || ' ' || FP.NOMEFUNC AS OBSERVACAO
, LCTB.DESCRLOCALCTB AS LOCAL_CONTABIL
, CC.DESCRCENTROCUSTO AS CENTRO_CUSTO
, EXTRACT(YEAR FROM PC.DATAFINALFOLHA) || lpad(EXTRACT(MONTH FROM PC.DATAFINALFOLHA), '2', '0') || EXTRACT(DAY FROM PC.DATAFINALFOLHA) AS VENCIMENTO
FROM CALCULORATEIO CR
LEFT JOIN CENTROCUSTO CC
ON CC.CODIGOEMPRESA = CR.CODIGOEMPRESA AND CC.CODIGOCENTROCUSTO = CR.CODIGOCENTROCUSTO
LEFT JOIN EVENTO EV
ON EV.CODIGOEVENTO = CR.CODIGOEVENTO
LEFT JOIN PERIODOCALCULO PC
ON PC.CODIGOEMPRESA = CR.CODIGOEMPRESA AND PC.CODIGOPERCALCULO = CR.CODIGOPERCALCULO
LEFT JOIN FUNCCONTRATO FC
ON FC.CODIGOEMPRESA = CR.CODIGOEMPRESA AND FC.CODIGOFUNCCONTR = CR.CODIGOFUNCCONTR
LEFT JOIN FUNCPESSOA FP
ON FP.CODIGOFUNCPESSOA = FC.CODIGOFUNCPESSOA
LEFT JOIN FUNCLOCALCTB FLC
ON FLC.CODIGOEMPRESA = CR.CODIGOEMPRESA AND FLC.CODIGOFUNCCONTR = CR.CODIGOFUNCCONTR
AND FLC.DATAOPCAO = (SELECT MAX(FLC1.DATAOPCAO) FROM FUNCLOCALCTB FLC1 WHERE FLC1.CODIGOEMPRESA = FLC.CODIGOEMPRESA AND
FLC1.CODIGOFUNCCONTR = FLC.CODIGOFUNCCONTR AND FLC1.DATAOPCAO <= PC.DATAINICIALFOLHA)
LEFT JOIN LOCALCONTABIL LCTB
ON LCTB.CODIGOEMPRESA = FLC.CODIGOEMPRESA AND LCTB.CODIGOLOCALCTB = FLC.CODIGOLOCALCTB
LEFT JOIN EVENTOTABELACONTABIL EVT
ON EVT.CODIGOEVENTO = CR.CODIGOEVENTO AND EVT.CODIGOGRUPOTABELACONTABIL = 0
LEFT JOIN TABCTBLOCALCTB TCL
ON TCL.CODIGOEMPRESA = FLC.CODIGOEMPRESA AND TCL.CODIGOTABCTB = EVT.CODIGOTABCTB AND TCL.CODIGOLOCALCTB = FLC.CODIGOLOCALCTB
WHERE
CR.CODIGOEMPRESA = :CodigoEmpresa.n AND
CR.CODIGOPERCALCULO = :CodigoPerCalculo.n
And here's one of the others:
SELECT
CASE
WHEN PFR.DIFERPGTO > 0 THEN '1608'
ELSE '1612'
END AS CONTA_CTB
, PFR.DIFERPGTO AS DEBITO
, PFR.DIFERPGTO AS CREDITO
, FP.NOMEFUNC AS FUNCIONARIO
, 'Diferença Pgto 13' || ' - ' || EXTRACT(MONTH FROM PC.COMPET) || '/' || EXTRACT(YEAR FROM PC.COMPET) || ' ' || FP.NOMEFUNC AS OBSERVACAO
, LCTB.DESCRLOCALCTB AS LOCAL_CONTABIL
, CC.DESCRCENTROCUSTO AS CENTRO_CUSTO
, EXTRACT(YEAR FROM PC.DATAFINALFOLHA) || lpad(EXTRACT(MONTH FROM PC.DATAFINALFOLHA), '2', '0') || EXTRACT(DAY FROM PC.DATAFINALFOLHA) AS VENCIMENTO
FROM PROVISAO13RAT PFR
LEFT JOIN FUNCCONTRATO FC
ON FC.CODIGOEMPRESA = PFR.CODIGOEMPRESA AND FC.CODIGOFUNCCONTR = PFR.CODIGOFUNCCONTR
LEFT JOIN FUNCPESSOA FP
ON FP.CODIGOFUNCPESSOA = FC.CODIGOFUNCPESSOA
LEFT JOIN PERIODOCALCULO PC
ON PC.CODIGOEMPRESA = PFR.CODIGOEMPRESA AND PC.COMPET = PFR.COMPET
LEFT JOIN CENTROCUSTO CC
ON CC.CODIGOEMPRESA = PFR.CODIGOEMPRESA AND CC.CODIGOCENTROCUSTO = PFR.CODIGOCENTROCUSTO
LEFT JOIN FUNCLOCALCTB FLC
ON FLC.CODIGOEMPRESA = PFR.CODIGOEMPRESA AND FLC.CODIGOFUNCCONTR = PFR.CODIGOFUNCCONTR
AND FLC.DATAOPCAO = (SELECT MAX(FLC1.DATAOPCAO) FROM FUNCLOCALCTB FLC1 WHERE FLC1.CODIGOEMPRESA = FLC.CODIGOEMPRESA AND
FLC1.CODIGOFUNCCONTR = FLC.CODIGOFUNCCONTR AND FLC1.DATAOPCAO <= PC.DATAINICIALFOLHA)
LEFT JOIN LOCALCONTABIL LCTB
ON LCTB.CODIGOEMPRESA = FLC.CODIGOEMPRESA AND LCTB.CODIGOLOCALCTB = FLC.CODIGOLOCALCTB
WHERE
PFR.CODIGOEMPRESA = :CODIGOEMPRESA.n AND
PFR.COMPET = :DATAINICIAL.d AND
PFR.DIFERPGTO <> 0
The main tables I'm using in these all have the same structures, with exception of that one (the first code I've pasted here), could this be part of the problem?
The WHERE clauses all filter through company code and billing date, that's the same for all of them. If any information is lacking, I'll provide them the best way I can.

Ok, so it turns out it was because of the table's structures that were different, doesn't really make much sense for me, but it's working now

Related

Add substring to an Inner Join

I want to replicate this query in my Power BI:
SELECT n.codigonotario,
n.nombrenotario,
CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN COUNT(cp.indiceunico)END AS NUM_OPERACIONES,
CASE SUBSTRING(dc.path, 11, 4)WHEN '0001' THEN SUM(cp.bases)END AS NUM_BASES,
SUM(dc.valornumerico / (CASE ISNULL(p.MONEDA, 0)WHEN 0 THEN 166.386 ELSE 1 END)) AS TotalCuantias,
RTRIM(LTRIM(cp.indiceunico)) AS codigoconcepto,
cp.textoconcepto + ' (' + RTRIM(LTRIM(cp.indiceunico)) + ')' AS DESCRIPCIONCONCEPTO,
cdc.categoriacampo
FROM notarios n
INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
INNER JOIN conceptosprotocolos cp ON cp.codigoprotocolo = p.codigoprotocolo
INNER JOIN datosconceptos dc ON dc.codigoprotocolo = p.codigoprotocolo
AND SUBSTRING(cp.path, 6, 4) = SUBSTRING(dc.path, 6, 4)
INNER JOIN camposdatosconceptos cdc ON cdc.codigocampodatos = dc.codigocampodatos
INNER JOIN conceptos c ON c.codigoconcepto = cp.codigoconcepto
WHERE p.fechaprotocolo >= '01/01/2022'
AND p.fechaprotocolo <= '31/12/2022'
AND n.codigonotario LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
AND (cdc.categoriacampo = 'CUANTIA'
OR cdc.categoriacampo = 'HONORARIOSBRUTO'
OR cdc.categoriacampo = 'HONORARIOSREDUCCION')
AND p.encargado LIKE CASE LEN('Prueba')WHEN 0 THEN '%' ELSE 'Prueba' END
AND (p.codigoprotocolo LIKE 'p%'
OR p.codigoprotocolo LIKE 'c%')
AND cp.indiceunico LIKE CASE LEN(1)WHEN 0 THEN '%' ELSE 1 END
GROUP BY n.codigonotario,
n.nombrenotario,
cp.indiceunico,
cp.textoconcepto,
dc.path,
cdc.categoriacampo;
I already have the database and tables imported in my project:
And I know how to implement inner joins:
But some of those inner joins need substrings and other functions, starting with the first inner join:
INNER JOIN protocolos p ON n.codigonotario = SUBSTRING(p.codigoprotocolo, 2, LEN(n.codigonotario))
You can't use SQL functions in Power BI, but you can use Power Query, so I'm struggling trying to replicate those here (it doesn't recognize 'MID' or 'LEFT').
let
Origen = Sql.Databases("LAPTOP-OSCAR"),
Far = Origen{[Name="Far"]}[Data],
dbo_NOTARIOS = Far{[Schema="dbo",Item="NOTARIOS"]}[Data],
#"Consultas combinadas" = Table.NestedJoin(dbo_NOTARIOS, {"CODIGONOTARIO"}, PROTOCOLOS, {"CODIGOPROTOCOLO"}, "PROTOCOLOS", JoinKind.Inner)
in
#"Consultas combinadas"
Could somebody help me to replicate the substring function in Power BI, please?

SQL Poor Performance on join query

i'm experiencing really poor performance with this query, probably because of my poor experience with join.
The following query have to run on a DB2 database.
SELECT A.n_ann_ord
|| A.n_prg_ord AS numeroOrdine,
DATE(B.d_ins) AS dataInserimentoEGO,
DATE(A.d_ord) AS dataInserimento,
C.n_lot_prd AS lotto,
E.t_rag_soc AS consorzio,
D.t_rag_soc AS cliente,
b.c_obu_new AS obuid,
j.c_tar AS targa,
j.c_naz AS nazione,
C.c_pos AS postazione,
CASE
WHEN B.f_ric_obu_sat = 'S' THEN 'Satellitare'
ELSE 'Non Satellitare'
END AS tipoTitolo,
F.t_des AS statoOrdine,
CASE
WHEN (SELECT 1
FROM evda.tetsau_sos_tit_mul X
WHERE x.d_ord = a.d_ord
FETCH first ROW only) = 1 THEN 'S'
ELSE 'N'
END AS SOSTITUZIONE,
DATE(G.d_ape_pro) AS aperturaLotto,
DATE(G.d_chiu_pro) AS chiusuraLotto,
DATE(G.d_com_con) AS confezionamento,
DATE(C.d_spe_spe) AS spedizione,
C.c_ide_spe AS trackingNumber,
DATE(H.d_acq_con) AS consegna
FROM evda.tetsvi_ord A
JOIN evda.tets3t_int_srv B
ON A.c_ctp_cli = B.c_ctp_cli
AND A.d_ord = B.d_ord
JOIN evda.tetski_int_con_ord C
ON A.c_ctp_cli = C.c_ctp_cli
AND A.d_ord = C.d_ord
JOIN evda.tets25_ctp D
ON C.c_ctp_cli = D.c_ctp
JOIN evda.tets25_ctp E
ON C.c_ctp_con = E.c_ctp
JOIN evda.tetsvk_sta_ord F
ON A.c_sta_ord = F.c_sta_ord
JOIN evda.tetsvp_pre_tit I
ON a.c_ctp_cli = i.c_ctp_cli
AND a.d_ord = i.d_ord
JOIN evda.tetsmj_tit_pre_est J
ON a.c_ctp_cli = j.c_ctp_cli
AND a.d_ord = j.d_ord
AND b.n_prg_tit_pre = j.n_prg
LEFT JOIN evda.tetskk_lot_prd G
ON C.n_lot_prd = G.n_lot_prd
LEFT JOIN evda.tets3u_int_srv_spe H
ON B.d_ins = H.d_ins
WHERE DATE(a.d_ord) <= CURRENT_DATE
AND DATE(a.d_ord) >= CURRENT_DATE - 30 DAYS
GROUP BY A.n_ann_ord
|| A.n_prg_ord,
DATE(B.d_ins),
DATE(A.d_ord),
C.n_lot_prd,
E.t_rag_soc,
D.t_rag_soc,
b.c_obu_new,
j.c_tar,
j.c_naz,
C.c_pos,
B.f_ric_obu_sat,
F.t_des,
a.d_ord,
DATE(G.d_ape_pro),
DATE(G.d_chiu_pro),
DATE(G.d_com_con),
DATE(C.d_spe_spe),
C.c_ide_spe,
DATE(H.d_acq_con)
Avoid using functions on table columns in where clause. Also, check whether "group by" is necessary as suggested by #jarlh
If d_ord is timestamp column, change where clause to
a.d_ord < timestamp( CURRENT_DATE + 1 days)
AND a.d_ord >= timestamp( CURRENT_DATE - 30 DAYS )

Unsure why ORA-00918 column ambiguously defined is appearing

I'm unsure as to why I'm getting the ORA-00918 error message appearing when I type in the following code.
I can't see which column is ambiguously defined.
What I want to do is create a table that pulls in the b.site_code value based on the work_header_no, work_version_no and site_numbers matching in queries A & B matching.
Code is below
SELECT
a.statement.statement_date,
a.sw_header.organise_code,
a.organisation.organise_name,
a.PermitRef,
a.actual_inspection.logged_time,
a.insp_category.insp_category_name,
a.actual_inspection.insp_number,
a.actual_inspection.site_number,
a.inspection_outcome.insp_outcome_name,
a.insp_category.insp_charge,
a.actual_inspection.insp_notes,
a.actual_inspection.work_header_no,
a.actual_inspection.insp_time,
b.site_code
FROM
(select
statement.statement_date,
sw_header.organise_code,
organisation.organise_name,
CAST(
organisation.external_ref_2 ||''||
sw_header.works_ref||'.'||
sw_notice_header.app_seq_no||'.'||
sw_notice_header.ext_version_no
as VARCHAR (40)) as PermitRef,
actual_inspection.logged_time,
insp_category.insp_category_name,
actual_inspection.insp_number,
actual_inspection.site_number,
inspection_outcome.insp_outcome_name,
insp_category.insp_charge,
actual_inspection.insp_notes,
actual_inspection.work_header_no,
actual_inspection.insp_time,
sw_notice_header.work_header_no,
sw_notice_header.work_version_no,
actual_inspection.site_number
from
actual_inspection
inner join sw_header on
actual_inspection.work_header_no = sw_header.work_header_no
inner join sw_notice_header on
sw_header.work_header_no = sw_notice_header.work_header_no
and sw_header.work_version_no = sw_notice_header.work_version_no
inner join insp_category on
actual_inspection.insp_category_code = insp_category.insp_category_code
inner join inspection_outcome on
actual_inspection.insp_outcome_code = inspection_outcome.insp_outcome_code
inner join organisation on
sw_header.organise_code = organisation.organise_code
inner join statement on
organisation.organise_code = statement.organise_code
and organisation.statement_number = statement.statement_no
where
actual_inspection.notice_type_code = '2600' and
actual_inspection.insp_outcome_code != 'O40'
order by
actual_inspection.logged_time)
a
JOIN
(
select
sns.work_header_no,
sns.work_version_no,
sns.site_number,
sns.site_code
from
sw_notice_site sns
)
b
ON a.work_header_no = b.work_header_no and
a.work_version_no = b.work_version_no and
a.site_number = b.site_number
You have duplicate actual_inspection.site_number and work_header_no remove the duplicate rows
actual_inspection.site_number,
inspection_outcome.insp_outcome_name,
insp_category.insp_charge,
actual_inspection.insp_notes,
actual_inspection.work_header_no,
actual_inspection.insp_time,
sw_notice_header.work_header_no,
sw_notice_header.work_version_no,
actual_inspection.site_number
No need to use a.statement.statement_date. You can use a.statement_date.
Likewise change all other columns for a..
Your whole query should look like this:
SELECT -- removed table names from all the columns
A.STATEMENT_DATE,
A.ORGANISE_CODE,
A.ORGANISE_NAME,
A.PERMITREF,
A.LOGGED_TIME,
A.INSP_CATEGORY_NAME,
A.INSP_NUMBER,
A.SITE_NUMBER,
A.INSP_OUTCOME_NAME,
A.INSP_CHARGE,
A.INSP_NOTES,
A.WORK_HEADER_NO,
A.INSP_TIME,
B.SITE_CODE
FROM
(
SELECT
STATEMENT.STATEMENT_DATE,
SW_HEADER.ORGANISE_CODE,
ORGANISATION.ORGANISE_NAME,
CAST(ORGANISATION.EXTERNAL_REF_2
|| ''
|| SW_HEADER.WORKS_REF
|| '.'
|| SW_NOTICE_HEADER.APP_SEQ_NO
|| '.'
|| SW_NOTICE_HEADER.EXT_VERSION_NO AS VARCHAR(40)) AS PERMITREF,
ACTUAL_INSPECTION.LOGGED_TIME,
INSP_CATEGORY.INSP_CATEGORY_NAME,
ACTUAL_INSPECTION.INSP_NUMBER,
--ACTUAL_INSPECTION.SITE_NUMBER, -- commented this as it is there in statement twice
INSPECTION_OUTCOME.INSP_OUTCOME_NAME,
INSP_CATEGORY.INSP_CHARGE,
ACTUAL_INSPECTION.INSP_NOTES,
ACTUAL_INSPECTION.WORK_HEADER_NO,
ACTUAL_INSPECTION.INSP_TIME,
--SW_NOTICE_HEADER.WORK_HEADER_NO, -- commented this as it is there in statement twice
SW_NOTICE_HEADER.WORK_VERSION_NO,
ACTUAL_INSPECTION.SITE_NUMBER
FROM
ACTUAL_INSPECTION
INNER JOIN SW_HEADER ON ACTUAL_INSPECTION.WORK_HEADER_NO = SW_HEADER.WORK_HEADER_NO
INNER JOIN SW_NOTICE_HEADER ON SW_HEADER.WORK_HEADER_NO = SW_NOTICE_HEADER.WORK_HEADER_NO
AND SW_HEADER.WORK_VERSION_NO = SW_NOTICE_HEADER.WORK_VERSION_NO
INNER JOIN INSP_CATEGORY ON ACTUAL_INSPECTION.INSP_CATEGORY_CODE = INSP_CATEGORY.INSP_CATEGORY_CODE
INNER JOIN INSPECTION_OUTCOME ON ACTUAL_INSPECTION.INSP_OUTCOME_CODE = INSPECTION_OUTCOME.INSP_OUTCOME_CODE
INNER JOIN ORGANISATION ON SW_HEADER.ORGANISE_CODE = ORGANISATION.ORGANISE_CODE
INNER JOIN STATEMENT ON ORGANISATION.ORGANISE_CODE = STATEMENT.ORGANISE_CODE
AND ORGANISATION.STATEMENT_NUMBER = STATEMENT.STATEMENT_NO
WHERE
ACTUAL_INSPECTION.NOTICE_TYPE_CODE = '2600'
AND ACTUAL_INSPECTION.INSP_OUTCOME_CODE != 'O40'
ORDER BY
ACTUAL_INSPECTION.LOGGED_TIME
) A
JOIN (
SELECT
SNS.WORK_HEADER_NO,
SNS.WORK_VERSION_NO,
SNS.SITE_NUMBER,
SNS.SITE_CODE
FROM
SW_NOTICE_SITE SNS
) B ON A.WORK_HEADER_NO = B.WORK_HEADER_NO
AND A.WORK_VERSION_NO = B.WORK_VERSION_NO
AND A.SITE_NUMBER = B.SITE_NUMBER;
Cheers!!

SQL query columns spreading

I have the following SQL query and as we see in the screenshot, there are two repeating row with the same constr_id(2015) value but with different assigned_insurance_packages.
Query:
select
ac.constr_id,
AIP.NAME as ASSIGNED_INSURANCE_PACKAGES,
ac.code,ac.constr_name,
ac.offer_name,
ac.repay_freq,
ac.min_amt,
ac.max_amt,
ac.min_downpay_percent,
ac.max_downpay_percent,
ac.downpay_amount,
ac.min_term,
(select
listagg(AF.NAME, '; ') within group(order by ACF.CONSTR_ID)
from
CREDILOGIC.ACQ_CONSTR_FEE acf, CREDILOGIC.ACQ_FEE af
where
ACF.CONSTR_ID = AC.CONSTR_ID and AF.FEE_ID = ACF.FEE_ID) as CONSTRUCTION_FEES,
INS_COMPANY.SHORT_NAME,
(select listagg(x.DURATION_MIN || '-' || TO_CHAR(x.RATE_SHIFT, '90.99') || ',' || x.DURATION_MAX || '-' || TO_CHAR(x.RATE_SHIFT, '90.99'), '; ') within group (order by X.CONSTRUCTION_ID)
from credilogic.ACQ_CONSTRUCTION_BASERATE x
where X.CONSTRUCTION_ID = AC.CONSTR_ID) as RATE
from
CREDILOGIC.ACQ_CONSTRUCTION ac
left join
CREDILOGIC.ACQ_CONSTR_INSPACKAGE aci on ACI.CONSTR_ID = AC.CONSTR_ID
and ACI.DELETED_TSTAMP is null
left join
CREDILOGIC.ACQ_INSURANCE_PACKAGE aip on AIP.INSURANCE_PACKAGE_ID = ACI.INSURANCE_PACKAGE_ID
left join
credilogic.ath_party ins_company ON INS_COMPANY.PARTY_ID = aip.PARTY_ID
left join
credilogic.ACQ_CONSTRUCTION_DUEDATE acd on ac.constr_id = acd.constr_id
left join
credilogic.ACQ_APPLICATION acp on ac.constr_id = acp.construction_id
I am just going to create two additional columns like 0.3% insurance pack and 0.5% insurance pack to put ASSIGNED_INSURANCE_PACKAGES values into different columns like in the picture below

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
)