SQL JOIN IF EXISTS - sql

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

Related

Qlik Sense : SQL With Statement

I'm using Qlik Sense Desktop in order to create reportings.
However, i want to load datas using this request :
WITH ventes AS (SELECT Reservations.re_numero AS IDSession, InscriptionsLignes.il_montantLigneHT AS VenteSession, Reservations.re_nom AS NomSession, Tiers.ti_nom AS NomClient, CASE WHEN Tiers_2.ti_nom + ' ' + Tiers_2.ti_prenom IS NULL THEN 'Non affecté' ELSE Tiers_2.ti_nom + ' ' + Tiers_2.ti_prenom END AS NomCommercial
FROM Reservations INNER JOIN
InscriptionsEntetes ON Reservations.re_numero = InscriptionsEntetes.in_reservation INNER JOIN
InscriptionsLignes ON InscriptionsEntetes.in_numero = InscriptionsLignes.il_inscription INNER JOIN
InscriptionsTiers ON InscriptionsEntetes.in_numero = InscriptionsTiers.it_inscription AND InscriptionsLignes.il_inscription = InscriptionsTiers.it_inscription INNER JOIN
Tiers ON InscriptionsTiers.it_tiers = Tiers.ti_identifiant LEFT OUTER JOIN
Tiers AS Tiers_2 ON InscriptionsEntetes.in_idTiersConseiller = Tiers_2.ti_identifiant
WHERE (InscriptionsTiers.it_typeRattachement = '01') AND (Reservations.re_etat <> 3) AND (Reservations.re_annulation = 0) AND (InscriptionsEntetes.in_Etat <> '4')), couts AS
(SELECT Reservations_1.re_numero AS IDSession, ReservationsProduits.rp_montantPrevu AS Couts
FROM Reservations AS Reservations_1 INNER JOIN
ReservationsProduits ON Reservations_1.re_numero = ReservationsProduits.rp_numeroReservation
WHERE (Reservations_1.re_etat <> 3) AND (Reservations_1.re_annulation = 0)), tot_couts AS
(SELECT IDSession, SUM(Couts) AS couts_total
FROM couts AS couts_1
GROUP BY IDSession), tot_ventes AS
(SELECT IDSession, SUM(VenteSession) AS ventes_total
FROM ventes AS ventes_1
GROUP BY IDSession)
SELECT tvn.IDSession, tvn.ventes_total, tct.couts_total, ventes_2.NomSession, ventes_2.NomClient, ventes_2.VenteSession, ventes_2.VenteSession - tct.couts_total / (tvn.ventes_total / ventes_2.VenteSession) AS marge
FROM tot_ventes AS tvn INNER JOIN
tot_couts AS tct ON tvn.IDSession = tct.IDSession INNER JOIN
ventes AS ventes_2 ON tvn.IDSession = ventes_2.IDSession
WHERE (ventes_2.VenteSession <> 0)
ORDER BY tvn.IDSession
As you can see, I'm using the SQL With Statement but it doesn't work on Qlik, "With" is a unknown statement they said
Anyone can help me ?
Some sql commands are just recongnize in Qlik if you use the SQL statement before, e.g.:
TableName:
LOAD *;
SQL ;
TableName:
LOAD *;
SQL
WITH ventes AS (
SELECT Reservations.re_numero AS IDSession
, InscriptionsLignes.il_montantLigneHT AS VenteSession
, Reservations.re_nom AS NomSession
, Tiers.ti_nom AS NomClient
, CASE
WHEN Tiers_2.ti_nom + ' ' + Tiers_2.ti_prenom IS NULL
THEN 'Non affecté'
ELSE Tiers_2.ti_nom + ' ' + Tiers_2.ti_prenom
END AS NomCommercial
FROM Reservations
INNER JOIN InscriptionsEntetes
ON Reservations.re_numero = InscriptionsEntetes.in_reservation
INNER JOIN InscriptionsLignes
ON InscriptionsEntetes.in_numero = InscriptionsLignes.il_inscription
INNER JOIN InscriptionsTiers
ON InscriptionsEntetes.in_numero = InscriptionsTiers.it_inscription
AND InscriptionsLignes.il_inscription = InscriptionsTiers.it_inscription
INNER JOIN Tiers
ON InscriptionsTiers.it_tiers = Tiers.ti_identifiant
LEFT OUTER JOIN Tiers AS Tiers_2
ON InscriptionsEntetes.in_idTiersConseiller = Tiers_2.ti_identifiant
WHERE (InscriptionsTiers.it_typeRattachement = '01')
AND (Reservations.re_etat 3)
AND (Reservations.re_annulation = 0)
AND (InscriptionsEntetes.in_Etat '4'))
, couts AS
(SELECT Reservations_1.re_numero AS IDSession
, ReservationsProduits.rp_montantPrevu AS Couts
FROM Reservations AS Reservations_1
INNER JOIN ReservationsProduits
ON Reservations_1.re_numero = ReservationsProduits.rp_numeroReservation
WHERE (Reservations_1.re_etat 3)
AND (Reservations_1.re_annulation = 0)), tot_couts AS
(SELECT IDSession, SUM(Couts) AS couts_total
FROM couts AS couts_1
GROUP BY IDSession), tot_ventes AS
(SELECT IDSession, SUM(VenteSession) AS ventes_total
FROM ventes AS ventes_1
GROUP BY IDSession)
SELECT tvn.IDSession
, tvn.ventes_total
, tct.couts_total
, ventes_2.NomSession
, ventes_2.NomClient
, ventes_2.VenteSession
, ventes_2.VenteSession - tct.couts_total / (tvn.ventes_total / ventes_2.VenteSession) AS marge
FROM tot_ventes AS tvn
INNER JOIN tot_couts AS tct
ON tvn.IDSession = tct.IDSession
INNER JOIN ventes AS ventes_2
ON tvn.IDSession = ventes_2.IDSession
WHERE (ventes_2.VenteSession 0)
ORDER BY tvn.IDSession;
You can encapsulate your query in a parent one:
TableName:
Load *;
SQL
select *
from (
--put your WITH query here
) as temp;
Depending on your RDBMS you might not need this final alias ("as temp").

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

Select with Sub Query

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.

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