Rownumber is not working as expected in report builder? - sql

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

Related

SQL Server query is taking 8 minutes to complete. All indexes are good

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

SQL to XML, combining two nodes

Currently I have a large SQL Server script that is outputting to XML. To summarize one of the nodes is duplicating. Below is the relevant snippet. I am looking consolidate some of the nodes into one but can't seem to get the syntax correct. See below for current and desired output examples.
DECLARE #CRWGroups TABLE (ClientID INT, intRegistrationWizardID INT, nvhProfileItemName VARCHAR(MAX), intProfileItemID INT, bitSelected BIT, intProfileItemOptionItemID INT, bitAnswer BIT
,dteAnswerStart DATE, decWeight DEC(5,2))
INSERT INTO #CRWGroups (ClientID, intRegistrationWizardID, nvhProfileItemName, intProfileItemID, bitSelected, intProfileItemOptionItemID, bitAnswer, dteAnswerStart, decWeight)
SELECT crw.intClientID, crw.intRegistrationWizardID, pi.nvhProfileItemName, crwegipi.intProfileItemID, crwegipi.bitSelected, pioi.intProfileItemOptionItemID,
crwegipib.bitAnswer, crwegipid.dteAnswerStart, pioi.decWeight from tblClientRegistrationWizard crw
INNER JOIN tblClientRegistrationWizardElement crwe ON crwe.intClientRegistrationWizardID = crw.intClientRegistrationWizardID
INNER JOIN tblClientRegistrationWizardElementGroup crweg ON crweg.intClientRegistrationWizardElementID = crwe.intClientRegistrationWizardElementID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItem crwegipi ON crwegipi.intClientRegistrationWizardElementGroupID = crweg.intClientRegistrationWizardElementGroupID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItemOptionItem crwegipioi ON crwegipioi.intClientRegistrationWizardElementGroupItemProfileItemID = crwegipi.intClientRegistrationWizardElementGroupItemProfileItemID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItemBool crwegipib ON crwegipib.intClientRegistrationWizardElementGroupItemProfileItemID = crwegipi.intClientRegistrationWizardElementGroupItemProfileItemID
LEFT JOIN tblClientRegistrationWizardElementGroupItem_ProfileItemDate crwegipid ON crwegipid.intClientRegistrationWizardElementGroupItemProfileItemID = crwegipi.intClientRegistrationWizardElementGroupItemProfileItemID
LEFT join tblProfileItem pi ON pi.intProfileItemID = crwegipi.intProfileItemID
LEFT JOIN tblProfileItemOptionItem pioi ON pioi.intProfileItemOptionItemID = crwegipioi.intProfileItemOptionItemID
LEFT JOIN tblProfileItemBool pib ON pib.intProfileItemID = crwegipib.intClientRegistrationWizardElementGroupItemProfileItemID
WHERE crw.intRegistrationWizardID = 49 AND (crwegipi.bitSelected = 1 OR crwegipib.bitAnswer = 1)
SELECT(
SELECT
(SELECT DISTINCT
CASE WHEN cg.intProfileItemID IN (5174,4864) THEN '10'
WHEN cg.intProfileItemID = 4862 THEN '11' END
FROM #CRWGroups cg WHERE cg.intProfileItemID IN (5174,4864,4862) AND cg.ClientID = c.ClientID
FOR XML PATH ('EmpStat'),type)
,(SELECT DISTINCT
CASE WHEN cg.intProfileItemID IN (4864,5174,4862) THEN (SELECT ISNULL(CASE WHEN CONVERT(DATE, cg.dteAnswerStart) = '1900-01-01' THEN '' ELSE CONVERT(CHAR(10), cg.dteAnswerStart, 120) END, '')) END
FROM #CRWGroups cg WHERE cg.intProfileItemID IN (4864,5174,4862) AND cg.ClientID = c.ClientID
FOR XML PATH ('DateEmpStatApp'),type)
,(SELECT CASE WHEN cg.intProfileItemID IN (5180) THEN (SELECT 'LOU' AS 'ESMType', '2' AS 'ESMCode' FOR XML PATH ('EmploymentStatusMonitoring'),type) END)
,(SELECT CASE WHEN cg.intProfileItemID IN (4868) THEN (SELECT 'BSI' AS 'ESMType', '1' AS 'ESMCode' FOR XML PATH ('EmploymentStatusMonitoring'),type) END)
FROM #CRWGroups cg WHERE cg.ClientID = c.ClientID AND cg.intProfileItemID IN (5180,4868)
FOR XML PATH ('LearnerEmploymentStatus'),type)
FROM tblClient c
INNER JOIN tblClientRegistrationWizard crw ON crw.intClientID = c.ClientID WHERE crw.intRegistrationWizardID = 49
Currently this snippet will produce the following result:
<LearnerEmploymentStatus>
<EmpStat>11</EmpStat>
<DateEmpStatApp>2017-06-05</DateEmpStatApp>
<EmploymentStatusMonitoring>
<ESMType>BSI</ESMType>
<ESMCode>1</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
<LearnerEmploymentStatus>
<EmpStat>11</EmpStat>
<DateEmpStatApp>2017-06-05</DateEmpStatApp>
<EmploymentStatusMonitoring>
<ESMType>LOU</ESMType>
<ESMCode>2</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
I am hoping to get it exporting in this format:
<LearnerEmploymentStatus>
<EmpStat>11</EmpStat>
<DateEmpStatApp>2017-06-05</DateEmpStatApp>
<EmploymentStatusMonitoring>
<ESMType>BSI</ESMType>
<ESMCode>1</ESMCode>
</EmploymentStatusMonitoring>
<EmploymentStatusMonitoring>
<ESMType>LOU</ESMType>
<ESMCode>2</ESMCode>
</EmploymentStatusMonitoring>
</LearnerEmploymentStatus>
Note there is only one EmploymentStatus node and contained inside are the two EmploymentStatusMonitoring nodes.

Grouping and Pipe delimiter (Newbee) SQL Server 2008 R2

I created this script:
SELECT Distinct
rtrim(Insurances.EligibilityPayorNumber) as InsurancePayorCode
, rtrim(ContractFacilityProviders.NPI) as ProviderID
, rtrim(PatientInsuranceProfiles.Insurance1PolicyNumber) as SubscriberInsuranceID
, rtrim(PatientInsuranceProfiles.Insurance1PolicyGroupNumber) as SubscriberGroupNumber
, rtrim(PatientDemographics.firstname) as SubscriberFirstName
, rtrim(PatientDemographics.MiddleInitial) as SubscriberMiddleInitial
, rtrim(PatientDemographics.Lastname) as SubscriberLastName
, rtrim(PatientDemographics.sex) as Gender
, rtrim(PatientDemographics.DateofBirth) as DOB
, ScheduleEntry.ScheduleDate as DateofService
, PatientDemographics.AccountNumber as TrackingID
FROM ScheduleEntry
LEFT JOIN PatientDemographics
ON ScheduleEntry.PatientAccount = PatientDemographics.AccountNumber
LEFT JOIN Reasons
ON ScheduleEntry.ReasonCode = Reasons.ReasonCode
LEFT JOIN Providers
ON ScheduleEntry.ResourceCode = Providers.MedStarProviderIdentifier
LEFT JOIN Facilities
ON ScheduleEntry.FacilityCode = Facilities.MedStarFacilityIdentifier
LEFT JOIN [john-pc\sqlexpress].[Global].[dbo].[PatientStatuses] TAB2
on ScheduleEntry.PatientStatus = TAB2.PatientStatusCode
LEFT JOIN AddedResource
ON ScheduleEntry.ResourceCode = AddedResource.AddedResourceCode
LEFT JOIN Caregiver
ON ScheduleEntry.ResourceCode = Caregiver.CaregiverCode
LEFT JOIN ReasonScripts
ON ScheduleEntry.ReasonCode = ReasonScripts.Reasoncode
LEFT JOIN Scripts
on Reasonscripts.Scriptcode = Scripts.ScriptCode
LEFT JOIN PatientInsuranceProfiles
ON ScheduleEntry.PatientAccount = PatientInsuranceProfiles.PatientAccountNumber
LEFT JOIN Insurances
ON PatientInsuranceProfiles.Insurance1Mnemonic = Insurances.Mnemonic
LEFT JOIN ContractFacilityProviders
ON PatientDemographics.PrimaryPhysician = ContractFacilityProviders.ProviderIdentifier
WHERE ScheduleEntry.ScheduleDate >= getdate()
and ScheduleEntry.ScheduleDate <= getDate() +1
and PatientinsuranceProfiles.ActiveFlag = 1
and EligibilityPayorNumber > = 1
ORDER By SCHEDULEDATE
I would like to do a few things and can't figure out how:
The DOB of is returning a value of Nov 6 1939 12:00AM and I need it to be mmddyyyy.
I need to group by TrackingID which can be the same on multiple lines. The data would always be the same.
What can I add to the script so when I run it as a SQL it will save as pipe delimited?
For your DOB, this can be used in your SELECT. Note, it will be of type VARCHAR and no longer a datetime.
SELECT REPLACE(CONVERT(VARCHAR(10),PatientDemographics.DateofBirth,101),'/','') AS DOB
I notice your RTRIM and they could be necessary for your output, but this is just some free knowledge on SQL server and trailing spaces for comparisions:
https://support.microsoft.com/en-us/kb/316626
DECLARE #s1 varchar(10)
DECLARE #s2 varchar(10)
set #s1 = 'nospace'
set #s2 = '3spaces '
select len(#s1), len(#s2)

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