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
)
Related
So I have a report that used this prod from sql like so:
alter PROCEDURE [dbo].[PHA00B01801_VN_BCThuocdakedontheoyeucau]
--declare
#TUNGAY DATETIME = '20220202',
#DENNGAY DATETIME = '20220204',
#KHODUOC_ID int = null,
#TENBACSI nvarchar(max) = null,
#MABENHVIEN VARCHAR(10)
AS
set #TENBACSI = ISNULL(#TENBACSI, '')
select st.TENBACSI, st.SOTOATHUOC, st.TENTHUOC, st.SOLUONG as SOLUONGTHUOC, st.KHOXUAT, st.GHICHU from
(
select nv.TENNHANVIEN as TENBACSI, ntkb.SOTHUTUTOA as SOTOATHUOC, d.TENDUOCDAYDU as TENTHUOC, nttt.SOLUONG as SOLUONG, ntkb.KHOXUAT_ID as KHOXUAT, nttt.GHICHU as GHICHU from TT_NGOAITRU_KHAMBENH_TOATHUOC as ntkb
inner join TT_NGOAITRU_TOATHUOC as nttt on nttt.KHAMBENH_TOATHUOC_ID = ntkb.KHAMBENH_TOATHUOC_ID
inner join TM_NHANVIEN as nv on nv.NHANVIEN_ID = ntkb.BACSI_ID
inner join TT_DUOC_CHUNGTU as ct on ntkb.CHUNGTUPHATTHUOC_ID = ct.CHUNGTU_ID
inner join TT_DUOC_CHUNGTU_CHITIET as ctct on ctct.CHUNGTU_ID = ct.CHUNGTU_ID
left join TM_DUOC as D on d.DUOC_ID = ctct.DUOC_ID
where ntkb.KHOXUAT_ID = #KHODUOC_ID or #KHODUOC_ID is null and CONVERT(DATE, CT.NGAYCHUNGTU) BETWEEN CONVERT(DATE,#TUNGAY) AND CONVERT(DATE,#DENNGAY)
group by nv.TENNHANVIEN, ntkb.SOTHUTUTOA, d.TENDUOCDAYDU, nttt.SOLUONG, ntkb.KHOXUAT_ID , nttt.GHICHU
union all
select nv.TENNHANVIEN as TENBACSI, NTT.SOTHUTUTOA as SOTOATHUOC, d.TENDUOCDAYDU as TENTHUOC, ntt.SOLUONG as SOLUONG, NKB.KHODUOC_ID as KHOXUAT, NTT.GHICHU as GHICHU from TT_NOITRU_KHAMBENH as NKB
inner join TT_NOITRU_TOATHUOC as NTT on NKB.KHAMBENH_ID = NTT.KHAMBENH_ID
inner join TM_NHANVIEN as nv on nv.NHANVIEN_ID = NKB.BACSIKHAM_ID
inner join TT_DUOC_CHUNGTU as ct on NTT.CHUNGTU_ID = ct.CHUNGTU_ID
inner join TT_DUOC_CHUNGTU_CHITIET as ctct on ctct.CHUNGTU_ID = ct.CHUNGTU_ID
left join TM_DUOC as D on d.DUOC_ID = ctct.DUOC_ID
where NKB.KHODUOC_ID = #KHODUOC_ID or #KHODUOC_ID is null and CONVERT(DATE, CT.NGAYCHUNGTU) BETWEEN CONVERT(DATE,#TUNGAY) AND CONVERT(DATE,#DENNGAY)
group by nv.TENNHANVIEN, NTT.SOTHUTUTOA, d.TENDUOCDAYDU, ntt.SOLUONG, NKB.KHODUOC_ID, NTT.GHICHU
) st where st.TENBACSI like '%' + #TENBACSI + '%'
group by st.TENBACSI, st.SOTOATHUOC, st.TENTHUOC, st.SOLUONG, st.KHOXUAT, st.GHICHU
order by st.TENBACSI
From that i used report builder to build a report where I group the TENBACSI aka doctors name and the SOTHUTUTOA aka the case id :
[1]: https://i.stack.imgur.com/NucZh.png
but when I tried to created row number for the 1st by using:
=RowNumber("TENBACSI")
It return wield Num Id such:
[2]: https://i.stack.imgur.com/HhDww.png
Then I tried to used:
=RunningValue(Fields!TENBACSI.Value,Count,"GROUP1")
Then I the result of all 1 in row number id.
I tried to look for answer but there is not much help
The following query below listed generates blank values in a row.
-- Simplify the pivot selection query by separating the query using a with clause
WITH pivot_data AS(
SELECT va.identity,
vc.units,
s.field_name "Sample ID",
s.id_text "Lab ID",
TO_CHAR(str.result_value, S_FORMATMASK_PACKAGE.s_FormatMask(vc.analysis, s.id_numeric))result_value
FROM sample s
LEFT OUTER JOIN client c ON c.id = s.client_id
LEFT OUTER JOIN samp_test_result str ON (s.id_numeric = str.id_numeric
AND s.id_text = str.id_text and str.result_value is not null)
LEFT OUTER JOIN versioned_analysis va ON (va.identity = str.analysis)
LEFT OUTER JOIN versioned_component vc ON (vc.analysis = va.identity
AND vc.analysis_version = va.analysis_version
AND vc.name = str.component_name)
WHERE s.fas_sample_type = sample_pkg.get_leaf_sample
AND s.status = sample_pkg.get_authorised_sample
AND s.flg_released = constant_pkg.get_true
AND vc.flg_report = constant_pkg.get_true
AND c.id = UPPER ('I000009')
AND s.ID_NUMERIC between TO_NUMBER(2126) and TO_NUMBER(12917) and str.result_value <> 0
)
SELECT pvt1.*
FROM(SELECT * FROM pivot_data PIVOT (MAX(result_value) result_value, MAX(units) units FOR identity IN('NIR_N' "Nitrogen",
'XRF_P' "Phosphorus",
'XRF_K' "Potassium",
'XRF_CA' "Calcium",
'XRF_MG' "Magnesium",
'XRF_S' "Sulphur",
'XRF_SI' "Silicon",
'XRF_ZN' "Zinc",
'XRF_MN' "Manganese",
'XRF_CU' "Copper",
'XRF_FE' "Iron"))) pvt1
How do I remove a row that contains null fields
Below is the query that I am running. Execution plan is at the bottom. It takes 8 minutes to complete and shows 'Query cost related to batch : 84%' in query plan.
I haves fixed some required non-cluster indexes but it saved hardly a minute in runtime.
Select distinct
ItemSolicitacao.IdItemSolicitacao As IdItemSolicitacao,
ItemSolicitacao.IdSolicitacao As IdSolicitacao,
ItemSolicitacao.IdItemAplicacao As IdItemAplicacao,
ItemSolicitacao.Mapeado As Mapeado,
ItemSolicitacao.IdFuncao As IdFuncao,
ItemSolicitacao.IdDepartamento As IdDepartamento,
ItemSolicitacao.IdDeptoGrupo As IdDeptoGrupo,
ItemSolicitacao.Removido As Removido,
ItemSolicitacao.AtividadeNome As AtividadeNome,
ItemSolicitacao.Acao As Acao,
Aplicacao.Nome As AplicacaoNome,
dbo.OwnersItemAplicacao(ItemSolicitacao.IdItemAplicacao, ItemSolicitacao.IdSolicitacao) As Owner,
case
when((select count(d.codigo) from ControleXerox..departamento as d
where d.deptoPai = Departamento.Codigo) != 0)
then 1
else 0
end as Grupo,
Departamento.Nome As DepartamentoNome,
DeptoOutro.Nome As DepartamentoGrupoNome,
Funcao.Nome As FuncaoNome,
TipoAplicacao.Nome As TipoAplicacaoNome,
TipoItemAplicacao.Nome As TipoItemAplicacaoNome,
ItemAplicacao.Nome As ItemAplicacaoNome
From
ItemSolicitacao
Inner Join
ItemAplicacao ON ItemSolicitacao.IdItemAplicacao = ItemAplicacao.IdItemAplicacao
Inner Join
Aplicacao ON ItemAplicacao.IdAplicacao = Aplicacao.IdAplicacao
Inner Join
TipoAplicacao ON TipoAplicacao.IdTipoAplicacao = Aplicacao.IdTipoAplicacao
Inner Join
TipoItemAplicacao ON ItemAplicacao.IdTipoItemAplicacao = TipoItemAplicacao.IdTipoItemAplicacao
left Join
ControleXerox..Departamento ON Departamento.Codigo = ItemSolicitacao.IdDepartamento
left Join
ControleXerox..Departamento as DeptoOutro ON DeptoOutro.Codigo = ItemSolicitacao.IdDeptoGrupo
left Join
ControleXerox..Funcao ON Funcao.Codigo = ItemSolicitacao.IdFuncao
Inner Join
AprovadorItemAplicacao ON AprovadorItemAplicacao.IdItemAplicacao = ItemAplicacao.IdItemAplicacao
Inner Join
Aprovador on AprovadorItemAplicacao.idAprovador = Aprovador.idAprovador
and AprovadorItemAplicacao.IdTipoAprovador = 1
https://www.brentozar.com/pastetheplan/?id=B1ND0biUQ
Please find the details of scalar function.
CREATE FUNCTION [dbo].[OwnersItemAplicacao]
(
#IdItemAplicacao INT
,#IdSolicitacao INT
)
RETURNS VARCHAR(2000)
AS
BEGIN
DECLARE #saida VARCHAR(2000)
SET #saida = ' '
DECLARE #owner VARCHAR(200)
DECLARE cur CURSOR
FOR
SELECT DISTINCT vc.Nome
FROM controlexerox..grupoEstacao
INNER JOIN controlexerox..view_colaboradores vc ON grupoEstacao.codEstacao = (
SELECT max(e.codigo)
FROM controlexerox..workflowItem wi
INNER JOIN controlexerox..estacao e ON e.codWorkflowItem = wi.codigo
AND wi.codigoItem = #IdSolicitacao
INNER JOIN controlexerox..grupoEstacao ge ON ge.codEstacao = e.codigo
AND ge.idItemAplicacao = #IdItemAplicacao
)
AND grupoEstacao.LoginS3Responsavel = vc.codigo
ORDER BY vc.Nome;
OPEN cur
FETCH NEXT
FROM cur
INTO #owner
WHILE ##FETCH_STATUS = 0
BEGIN
SET #saida = #saida + CHAR(10) + #owner
FETCH NEXT
FROM cur
INTO #owner
END
CLOSE cur
DEALLOCATE cur
RETURN substring(#saida, 3, len(#saida))
END
This code is 100% untested because I have nothing to work with. But something along these lines should let you completely eliminate that scalar function. Keep in mind that sql is a declarative language and works best with sets. Doing processing RBAR (row by agonizing row) is going to suck the life out of your server.
Give this code a shot and see if it gets you pointed the right way.
Select distinct
s.IdItemSolicitacao
, s.IdSolicitacao
, s.IdItemAplicacao
, s.Mapeado
, s.IdFuncao
, s.IdDepartamento
, s.IdDeptoGrupo
, s.Removido
, s.AtividadeNome
, s.Acao
, a.Nome As AplicacaoNome
--, dbo.OwnersItemAplicacao(s.IdItemAplicacao, s.IdSolicitacao) As Owner
, Owner = x.NameList
, case when (select count(d.codigo) from ControleXerox..departamento as dept where dept.deptoPai = d.Codigo) != 0 then 1 else 0 end as Grupo,
, d.Nome As DepartamentoNome
, DeptoOutro.Nome As DepartamentoGrupoNome
, f.Nome As FuncaoNome
, Tipoa.Nome As TipoAplicacaoNome
, Tipoia.Nome As TipoItemAplicacaoNome
, ia.Nome As ItemAplicacaoNome
From ItemSolicitacao s
Inner Join ItemAplicacao ia ON s.IdItemAplicacao = ia.IdItemAplicacao
Inner Join Aplicacao a ON ia.IdAplicacao = a.IdAplicacao
Inner Join TipoAplicacao Tipoa ON Tipoa.IdTipoAplicacao = a.IdTipoAplicacao
Inner Join TipoItemAplicacao Tipoia ON ia.IdTipoItemAplicacao = Tipoia.IdTipoItemAplicacao
left Join ControleXerox..Departamento d ON d.Codigo = s.IdDepartamento
left Join ControleXerox..Departamento as DeptoOutro ON DeptoOutro.Codigo = s.IdDeptoGrupo
left Join ControleXerox..Funcao f ON f.Codigo = s.IdFuncao
Inner Join AprovadorItemAplicacao Aprovadoria ON Aprovadoria.IdItemAplicacao = ia.IdItemAplicacao
Inner Join Aprovador ON Aprovadoria.idAprovador = Aprovador.idAprovador
and Aprovadoria.IdTipoAprovador = 1
outer apply
(
select NameList = STUFF((select char(10) + vc.Nome
FROM controlexerox..grupoEstacao ge
INNER JOIN controlexerox..view_colaboradores vc ON ge.codEstacao =
(
SELECT max(e.codigo)
FROM controlexerox..workflowItem wi
INNER JOIN controlexerox..estacao e ON e.codWorkflowItem = wi.codigo
AND wi.codigoItem = s.IdSolicitacao
INNER JOIN controlexerox..grupoEstacao ge ON ge.codEstacao = e.codigo
AND ge.idItemAplicacao = s.IdItemAplicacao
)
AND grupoEstacao.LoginS3Responsavel = vc.codigo
group by vc.Nome
ORDER BY vc.Nome
FOR XML PATH('')), 1, 1, '')
) x
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").
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